Menu
  • HOME
  • TAGS

How would I link to an external site from a cell in a kendo grid?

c#,asp.net-mvc-4,kendo-ui,kendo-grid

here is example based on the kendo dojo <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Untitled</title> <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.1.528/styles/kendo.common.min.css"> <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.1.528/styles/kendo.rtl.min.css"> <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.1.528/styles/kendo.default.min.css"> <link rel="stylesheet"...

MVC 4 - pass parameter to controller on button click

asp.net-mvc-4

The input buttons have a value. You can detect the value of the input button at the controller. <input type="submit" value="submitbutton"> <input type="submit" value="savebutton"> ...

Prevent page refresh on submit button click

asp.net-mvc-4

In the server-side validation ,the page must be submitted via a postback to be validated on the server and if the model data is not valid then the server sends a response back to the client. With client-side validation, the input data is checked as soon as they are submitted,...

check for value null on razor syntax

c#,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-4,razor

try this: @{ if (propiedadesFormularioDetalle != null) { <div class="panel panel-default"> <div class="panel-heading">Propiedades adicionales</div> <div class="panel-body"> <dl class="dl-horizontal"> foreach (KeyValuePair<string, string> propiedad in propiedadesFormularioDetalle) { <dt> Html.DisplayName(propiedad.Key) </dt> <dd> Html.DisplayFor(prop => propiedad.Value) </dd> } </dl> </div> } </div> } ...

Why does my MVC binding stop working when I assign a nested model to a variable?

c#,asp.net-mvc,asp.net-mvc-4,razor

If you inspect the html you are generating you will see that they are not the same. Your first code block generates html like <input name="NestedModel[0].Id" id="NestedModel_0__Id" .../> <input name="NestedModel[1].Id" id="NestedModel_1__Id" .../> The second one will generate html like <input name="nestedModel.Id" id="nestedModel_Id" .../> <input name="nestedModel.Id" id="nestedModel_Id" .../> The second generates...

Is it possible to access an additional custom model property from viewdata.modelmetadata.properties?

asp.net-mvc-4

Above, Stephen was able to point me in the right direction. My additional attribute was there the whole time, and I didn't even need the helper class, just the IMetaDataAware. @foreach (var property in ViewData.ModelMetadata.Properties) { <div style="margin:10px"> <strong>@(property.DisplayName)</strong> <br /> @foreach (var addProp in property.AdditionalValues) { if (addProp.Key ==...

Jquery Tabs - return selected tab dynamically

c#,jquery,asp.net-mvc,asp.net-mvc-4,razor

I got this to work, not sure if best approach. $("#tabs").tabs( { active: $("#SelectedTabToFind").val(), cache: false }); I set the value of SelectedTabToFind in the controller....

How to add validators for @Html.TextBox() without model

asp.net-mvc,asp.net-mvc-4

Add data-val and data-val-required attribute for Html.TextBox() as shown below. <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> @using (Html.BeginForm("","")) { @Html.ValidationSummary() @Html.TextBox("bill_address", null, new { @class = "form-control valid", @data_val = "true", @data_val_required = "Billing Address is required" }) <input type="submit" value="Click"...

Mvc Remote Attribute is sending “undefined” in query string

c#,asp.net,asp.net-mvc,asp.net-mvc-4

You need to add @Html.HiddenFor(m=>m.UserId) at the view so that the binder will bind it to the remote validation controller or otherwise there is no value to bind ...

Need to Close the div in if condition MVC View

asp.net-mvc,asp.net-mvc-4

I think you need something like this, run two loops one for total and one for two items. so this condition of loose close elements will not occur. @for (int count = 0; count <= ViewBag.modal.Count; count++) { <div class="Class1"> @for (int counter = 0; counter < 2 && (count...

Using Bootstrap 3 DateTimePicker in ASP.NET MVC Project

jquery,asp.net-mvc,twitter-bootstrap,asp.net-mvc-4,bootstrap-datetimepicker

The easiest way in MVC with bootstrap would be to set the properties in your model with DataAnnotations. Here is a link that should help you. Using Data Annotations for Model Validation [DisplayName("Owners Date of Birth:")] Will display in the @Html.LabelFor and this will be the label for your field....

How do you send data to controller with ajax.beginform?

ajax,asp.net-mvc-4,razor,model-view-controller,model

To make you understand how AJAX FORM works, I created below code - Lets say our model - public class Sale { public string SaleOwner { get; set; } public virtual Account Account { get; set; } } public class Account { public string Name { get; set; } }...

Conflicted with the REFERENCE constraint. How to solve this?

asp.net-mvc-4,nhibernate

Judging by that error, your repository is trying to delete the a user from its table but that user is referenced in another table (dbo.Invoices). So you are seeing a foreign key constraint error where you are trying to delete a record who's primary key is referenced in another table...

Get desired html element's attribute value and set to hidden field before binding in Asp.Net MVC

c#,.net,asp.net-mvc,asp.net-mvc-4,asp.net-mvc-5

The clearest solution is to use radio button with style. In fact, your code act as a radio button; the only difference is the icon-check, but you can emulate the same interface with CSS.

MVC Routing News Pages

asp.net-mvc-4,asp.net-mvc-routing

One way you could do this is to introduce an additional route into the route configuration RouteConfig.cs: routes.MapRoute( name: "News_seo_friendly", url: "{controller}/{id}/{seo}", defaults: new { action = "NewsItem", seo = UrlParameter.Optional } ); *Note the action value in this route. You will need a corresponding action method on that controller....

How to consume multipart/form data request in C# mvc 4 webservice

c#,asp.net-mvc,web-services,wcf,asp.net-mvc-4

Check Request.Files variable. foreach (string file in Request.Files) { var postedFile = Request.Files[file]; postedFile.SaveAs(Server.MapPath("~/UploadedFiles") + pelicula.Id); } ...

Mvc: Getting the selected value of the dropdownlistFor box

asp.net-mvc-4

A <select> element postback a single value. You cannot bind a <select> to a collection of complex objects (in your case List<DepartmentDto>). Start by creating a view model representing what you want to edit public class StudentVM { [Display(Name = "First Name")] [Required(ErrorMessage = "Please enter your first name")] public...

Unable to make parent li active on click of child li with bootstrap in mvc4

c#,asp.net,asp.net-mvc-4,c#-4.0

There are 2 things to do, one is make the active selection when user clicks and the other is save this selection after the page refreshs right? If you want to make li selected after the page refresh you need to save this state somewhere. You can save it in...

MVC HandlerError attribute isn't redirecting to error View on Exception

c#,asp.net-mvc,asp.net-mvc-4

You cannot redirect via an AJAX post. You can send back the URL to the frontend to which you want to redirect the browser to and then use JS to navigate there. Backend - Home Controller [HttpPost] public ActionResult GoToMethodName() { return Json(Url.Action("Index", "MethodName")); } Views JS - This is...

Call back from server to client

c#,asp.net,asp.net-mvc,asp.net-mvc-4

You have to write an ActionResult that progressively write result to the response. so you can show the user some data in every foreach loop iteration. I have written a simple ActionResult that writes a number every 2 seconds: public class ProgressiveResult : ActionResult { public override void ExecuteResult(ControllerContext context)...

MVC 5 OWIN login with claims and AntiforgeryToken. Do I miss a ClaimsIdentity provider?

asp.net-mvc,asp.net-mvc-4,razor,asp.net-mvc-5,claims-based-identity

Your claim identity does not have ClaimTypes.NameIdentifier, you should add more into claim array: var claims = new List<Claim> { new Claim(ClaimTypes.Name, "Brock"), new Claim(ClaimTypes.Email, "[email protected]"), new Claim(ClaimTypes.NameIdentifier, "userId"), //should be userid }; To map the information to Claim for more corrective: ClaimTypes.Name => map to username ClaimTypes.NameIdentifier => map...

Delete Confirmation Window

jquery,asp.net-mvc,asp.net-mvc-4,telerik

Every time you call the DeleteItem function you are setting up a handler for the #yes button to delete a specific row. Even if you cancel and select a different row, the handler was already set, and will run on a future click of the button. To avoid this, you...

404 when converting asp.net mvc app to angularjs

c#,asp.net,asp.net-mvc,angularjs,asp.net-mvc-4

MVC pattern means the controller takes requests and renders views. You are trying to bypass that and the Views/web.config prevents that. You can either render your view via the Controller (MVC-style), or configure a section of your app to serve static files ...

Dynamically adding controls in MVC4

asp.net-mvc,asp.net-mvc-4

You can create a editor template and pass the control list as model to the template and in the template you can iterate that list to generate the control. As i have shown below. 1->Create a class for Control Information. public class ControlInfo { public string ControlType { get; set;...

MVC Hidden field via HTML Helper in Form Post issue

c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor

Although not obvious and I found it difficult to find many articles on this subject to clarify it for me in the past the default behaviour in ASP.NET MVC is the following: If you are using HTML Helpers and you are rendering the same View in response to a POST...

How to Implement Dependent Dropdownlist in MVC4 Razor and using SQL server also

sql-server,asp.net-mvc-4,razor

Note : As per your requirement you need to show country name when user selects the state then why you need dropdownlist for country ?? it is better to use a label for that. For you requirement first you have to maintain a table which stores country and it's state...

Pass a javascript variable as parameter to @url.Action()

javascript,asp.net-mvc-4,url.action

You need to build you url using javascript/jquery. In the view change the link to <a id="export" href=#">Export as CSV</a> Then in the script var baseurl = '@Url.Action("Export")'; $('#export').click(function() { var url = baseurl + '?SelectedAccountType=' + $('#SelectedAccountType').val() + '&FromDate=' + $('#FromDate').val() + '&ToDate=' + $('#ToDate').val() + ...etc location.href=url; });...

Display value of a textbox inside another textbox using AngularJs on button click

angularjs,asp.net-mvc-4

in your controller do , $scope.myFunction = function () { $scope.display = $scope.type; } in your html you have to change onclick to ng-click, <input type="button" value="button" ng-click="myFunction()" /> see this plunk for example, http://plnkr.co/edit/c5Ho1jlixwZFx7pLFm9D?p=preview...

select random data from database in mvc4 C#

c#,asp.net-mvc-4

Do this: (from p in products orderby Guid.NewGuid() select p).Take(10).ToList() ...

Get selected data

c#,asp.net,asp.net-mvc,asp.net-mvc-4

Firstly to address why no data is being loaded. In your Update() method you first initialize a new instance of ManageUser, whose default value for Username will be null (the default for typeof string). You then call user.GetData(user.Username); which passes null to the method and based on if (string.IsNullOrEmpty(Username)) //...

How to Upload file onclick of button of type=button not type=submit in mvc4 using html begin form

file,asp.net-mvc-4,button,upload,submit

@using(Html.BeginForm("Upload","Home",new {@id="frm"})) { <input type="file" id="upld" /> <input type="button" value="upload" id="btn" /> } <script> $('#btn').click(function(){ var has_selected_file = $('#upld').filter(function(){ return $.trim(this.value) != '' }).length > 0 ; if(has_selected_file){ $('#frm').submit(); } else{ alert('No file selected'); } }); I hope this is your requirement ...

Setting up routing when RemoteAttribute specifies AdditionalFields

c#,asp.net,asp.net-mvc,asp.net-mvc-4

When it receives a query such as /Validation/IsUserNameAvailable?userName=BOB&UserID=, MVC's model binder is confused because it does not know how to handle null/empty string params. Just change the param to an int and cast as necessary for your helper method: public JsonResult IsUserNameAvailable(string userName, int UserId) { var users = new...

How do I set the URL for a new page/view when using ASP.NET MVC

c#,asp.net,asp.net-mvc,asp.net-mvc-4

You'll have a file called RouteConfig.cs in App_Start. This defines the relationship between the url and the controller/action. If no-one has changed this, it will look like: routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } http://localhost/Example will match the default...

Saving child entity is not saving the foreign key with entity framework

c#,asp.net-mvc,asp.net-mvc-4

In the declaration on DataAnnotation Bind at the Create method, you are not including Entidad property, never will be binded, just remove the Bind DataAnnotation or include it.

RedirectToAction to another Controller and passing parameters

c#,asp.net,asp.net-mvc,asp.net-mvc-4

The DefaultModelBinder cannot initialize an instance or your Error class based on the query string parameters because you have private set on all your properties. Your model should be public class Error { public String name { get; set; } public String description { get; set; } public int number...

ApplicationUser ICollection member not being saved in DB

c#,.net,entity-framework,asp.net-mvc-4,asp.net-mvc-5

You need to model your collection items. You could go many to many or one to many. // many to many public class Interest { public int InterestId { get; set; } public string InterestDesc { get; set; } // field can't match class name } // one to many...

mvc 4 custom format validator does not show error and allows the form to submit

asp.net-mvc,validation,asp.net-mvc-4

In order to get client side validation, your attribute must implement IClientValidatable and you must include a client side script that adds a method to the client side $.validator object. This article THE COMPLETE GUIDE TO VALIDATION IN ASP.NET MVC 3 gives some good examples of how to implement it....

Why mozilla changes the characters when i use the .net mvc statement redirect?

c#,asp.net-mvc-4,redirect,mozilla

%E2%80%8B is a URL-encoded, UTF-8 encoded ZERO-WIDTH SPACE character. You likely have one hiding in your application setting file for the ProActiveOffice-URL value. It was maybe pasted in that way, if you copied the URL from somewhere.

How to add an Option label on ListBoxFor HTML Helper in ASP.Net MVC

asp.net-mvc,asp.net-mvc-4,html-helper

The reason that Html.DropDownListFor() has an "option" parameter is that dropdown lists, when they don't have a selected value, are blank and you can't see their contents without expanding them. Listboxes, typically do display their contents, and thus an option is not necessary. An unselected listbox doesn't need something to...

C# mvc4 - direct URL to controller

c#,asp.net-mvc-4,url,redirect

You might have forgotten to specify name of the controller in Html.ActionLink() parameter. Try Html.ActionLink("actionname","controllername");

Set JQuery propeties to Image folder path in img src tag

javascript,jquery,html,image,asp.net-mvc-4

Just create a baseUrl in script tag in your layout page. <script type="text/javascript"> var baseUrl = "@Url.Content("~")"; </script> and use that in your script like below: $(document).ready(function () { $('.bxslider').bxSlider({ nextSelector: '#slider-next', prevSelector: '#slider-prev', controls: true, pager: false, nextText: '<img src="'+baseUrl +'Images/rightArrow.jpg" height="25" width="25"/>', prevText: '<img src="'+baseUrl +'Images/leftArrow.jpg" height="25" width="25"/>'...

Rendering “~/bundles/jqueryval”

c#,asp.net-mvc,asp.net-mvc-4,razor

You need to declare the section within your "master page": @RenderSection("Scripts", false) Probably the best idea to include this in the head tag. Otherwise it doesn't know what to do with your Scripts section defined in your child view. The second parameter, which I've set to false is whether or...

File upload control in asp.net mvc

c#,asp.net,asp.net-mvc,asp.net-mvc-4

try this: You can Get Stream From InputStream of Fileuplpad Control then you can convert Stream to byte Array for saving into database Stream stream = file.PostedFile.InputStream; byte[] byteArray = ReadFully(stream); public static byte[] ReadFully(Stream input) { byte[] buffer = new byte[input.Length]; using (MemoryStream ms = new MemoryStream()) { int...

Return to the same view when no image is selected

asp.net-mvc-4,razor,json.net,entity-framework-5,c#-5.0

Add a ModelState error and return the view (otherwise redirect), for example if (isSavedSuccessfully) { return Redirect(Url.Action("Edit", "Account") + "#tabs-2"); } else { ModelState.AddModelError("Image", "your message"); return View(user); } ...

How can I bind a list model which contains a complex type in MVC4?

c#,asp.net-mvc,asp.net-mvc-4

You can use javascript to handle onsubmit event and merge data from those two fields into one that will be parsed as DateTime. Do you need some code to see how it could be done?

MVC Push notification from server to client side

asp.net-mvc-4,push-notification

You can use SignalR : $.connection.hub.start().done(function () { $('#sendmessage').click(function () { // Call the Send method on the hub. chat.server.send($('#displayname').val(), $('#message').val()); // Clear text box and reset focus for next comment. $('#message').val('').focus(); }); }); use more info: tutorial...

Partial View's checkbox state not returned to controller

c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor

asp.net MVC model binding can only bind to one model. To solve your issue you would simply need to create a base class that all your models, that may use a FacilityList , would derive from. Like so: public class FacilityViewModel { public Dictionary<string, bool> FacilityList { get; set; }...

How to download a file through ajax request in asp.net MVC 4

jquery,json,asp.net-mvc-4,asp.net-ajax

Please, try this in ajax success success: function () { window.location = '@Url.Action("DownloadAttachment", "PostDetail")'; } Updated answer: public ActionResult DownloadAttachment(int studentId) { // Find user by passed id // Student student = db.Students.FirstOrDefault(s => s.Id == studentId); var file = db.EmailAttachmentReceived.FirstOrDefault(x => x.LisaId == studentId); byte[] fileBytes = System.IO.File.ReadAllBytes(file.Filepath); return...

ASP .Net MVC get decorated roles for unathorized request

c#,asp.net,asp.net-mvc,asp.net-mvc-4

The AuthorizeAttribute has a property called Roles that you should be able to check to get the information you want. As mentioned by @EricFunkenbusch you can assume that the user is not in any of those roles. https://msdn.microsoft.com/en-us/library/dd460323(v=vs.118).aspx...

How to get started with Visual studio 2012

c#,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-4,visual-studio-2012

Download this book "Microsoft ASP.NET 4 Step By Step" by George Shepherd.I found it very helpful.It will address all the issues you raised here.Thank you.

Setting up IdentityServer wtih Asp.Net MVC Application

c#,asp.net-mvc-4,identityserver3

You need to request the scopes required by the api when the user logs in. Scope = "openid profile roles baseballStatsApi" Authority = "https://localhost:44301/identity", ClientId = "baseballStats", Scope = "openid profile roles baseballStatsApi", ResponseType = "id_token token", RedirectUri = "https://localhost:44300/", SignInAsAuthenticationType = "Cookies", UseTokenLifetime = false, ...

Retrieve all data from the database got the second row same with the first row

c#,mysql,asp.net-mvc-4

Your error occurs because you declare just one instance of context, and the keep updating its UserName in the while loop (inside the while loop you just add another reference of it to the collection) You need to declare a new instance inside the loop while (reader.Read()) { UserContext context...

Bind multiselect selections to list of objects

c#,asp.net,asp.net-mvc,asp.net-mvc-4

You have to create an [] or List of IDs in the ViewModel that will store selected values. public class ListingPlanEditorViewModel { public ListingPlan Plan { get; set; } public IEnumerable<Directory> SiteDirectories { get; set; } public int[] DirectoryIDs {get;set;} } The View will change according. The Directories selected will...

Use Bearer Token Authentication for API and OpenId authentication for MVC on the same application project

c#,asp.net-mvc-4,oauth-2.0,openid,identityserver3

Ok, I found some information on the following post https://github.com/IdentityServer/IdentityServer3/issues/487 The github repo that implements the concepts discussed in the link can be found here https://github.com/B3nCr/IdentityServer-Sample/blob/master/B3nCr.Communication/Startup.cs Basically you need to map the api url to a different configuration using app.Map(). In my case, I changed my startup file to look...

Redirect to a different MVC controller when supplying an empty URL parameter?

c#,asp.net-mvc,asp.net-mvc-4

If you pass the parameter in function we need put then or set a initial value. int pageNo = 0 or int? pageNo [HttpGet] public ActionResult FutureEvents(int pageNo = 0) { //code } all others functions without parameters open normally....

C# Using Bool, how to check a double is truly divisible by another number? [duplicate]

c#,asp.net-mvc-4

You can use the %-operator: bool isDivisible = 1115 % 100 == 0; The % operator computes the remainder after dividing its first operand by its second. All numeric types have predefined remainder operators. ...

Protractor, login to asp,net MVC login page, wait for default page then , redirect to angular page and do tests…how?

c#,angularjs,asp.net-mvc-4,selenium,protractor

If you know which URL ends the redirect chain, you can use browser.wait() to wait for current URL to become equal to an expected one: var urlChanged = function(expectedUrl) { return function () { return browser.getCurrentUrl().then(function(actualUrl) { return expectedUrl === actualUrl; }); }; }; browser.wait(urlChanged("http://url.to/wait/for"), 5000); ...

Return MVC view while submitting serialized data(MVC, Ajax)

jquery,ajax,asp.net-mvc,asp.net-mvc-4

You don't need json serialization nor AJAX. First create a class to hold your form fields. public class EmailForm { public string Name { get; set; } public string Address { get; set; } public string Message { get; set; } } Then your form will match the EmailForm property...

C# entity framework MVC second run error

entity-framework,asp.net-mvc-4,localdb

Your initialiser is using the DropCreateDatabaseAlways class which, as it suggests, drops that database every time the application is initialised. Instead perhaps you could use CreateDatabaseIfNotExists or DropCreateDatabaseIfModelChanges: public class ComponentDbInitialize : CreateDatabaseIfNotExists<ComputerContext> { } ...

Exact need of jquery.validate.js

jquery,asp.net-mvc-4,jquery-validate

jQuery Validate is just an addon for jQuery you could use. So you still got to write the validation yourself, even though jQuery Validate makes a lot of things easier. Here is a documentation on the plugin you should check out, to use it for your needs....

MVC best practice for displaying static generated data

c#,asp.net-mvc,asp.net-mvc-4,razor

Based on the principle of not gold plating your code. You don't need the view model (right now) so don't add it. If you want a view model later then it's simple to add one. Your goal should be to create the simplest solution possible. For me that means the...

@Html.RadioButtonFor in mvc

c#,asp.net-mvc-4,razor

You need to change you model to represent what you want to edit. It needs to include a property for the selected User.Id and a collection of users to select from public class SelectUserVM { public int SelectedUser { get; set; } // assumes User.Id is typeof int public IEnumerable<User>...

Asp.net MVC Routelink null controller parameter

c#,asp.net,asp.net-mvc,asp.net-mvc-4,routing

You cannot have TWO Routes with same parameters and same definition, first one will take precedence. Instead, you need to have something like shown below with specific constraints in routes. routes.MapRoute( name: "ByName", url: "sample/{action}/{name}", defaults: new { controller = "Home", action = "Index", name = UrlParameter.Optional } ); routes.MapRoute(...

how to use Html.RenderPartial with ViewModel

asp.net-mvc,asp.net-mvc-4,asp.net-mvc-partialview,renderpartial

There is a difference between RenderAction and RenderPartial. In the first you are calling action, but in second, you are directly calling partial view. So you cannot pass productId in RenderPartial, instead you need to pass List<ProductViewModel>. Also in RenderPartial, you need to give partial view name, not the action...

Using dropdownlistfor for model with list property

c#,asp.net-mvc,asp.net-mvc-4,model

You can put the selected id into your viewmodel. public class ViewModel { public IEnumerable<SelectListItem> Model1Items{ get; set; } public int SelectedId { get; set; } } public class Model1{ public int Id {get; set;} public string Name {get; set;} } In the Controller: var items = (from m in...

How to store a string in xml file and use it in _Layout in MVC

c#,xml,asp.net-mvc,asp.net-mvc-4

Sourced: from this link The web.config (or app.config) is a great place to store custom strings: in web.config: <appSettings> <add key="message" value="Hello, World!" /> </appSettings> in cs: string str = ConfigurationSettings.AppSettings["message"].toString(); ...

jQuery: How to traverse / Iterate over a list of object

javascript,jquery,asp.net-mvc,asp.net-mvc-4,razor

Assign your collection to a javascript variable using var users = JSON.parse('@Html.Raw(Json.Encode(Model.AllUsers))'); which you can then iterate over $.each(users, function(index, item) { // access the properties of each user var id = item.Id; var name = item.Name; .... }); ...

MVC - How to render a 'a href' link in a View that's been stored in a database?

asp.net-mvc,asp.net-mvc-4,model-view-controller

Try this: <h4>@Html.Raw(Model.HomePageVM.AboutUsDescOne)</h4> Use this helper with caution though. If a user can edit this block of HTML then you might be making yourself vulnerable to an XSS attack: Text output will generally be HTML encoded. Using Html.Raw allows you to output text containing html elements to the client, and...

mvc - Html.BeginForm postbacks to wrong controller

asp.net-mvc-4,html.beginform

I managed to solve this issue by moving partial view to Shared folder.

Form Post Not working While Submission

c#,asp.net,asp.net-mvc,asp.net-mvc-4

You have to fix your connection. But incorrect connection string may have different causes. Try to connect to your database with Server Explorer in Visual Studio then select your database and press F4 (Properties). You can see the correct connection string there. Put it in connection string in your web.config.

Why is my View not displaying value of ViewBag?

c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor

ViewBag is used when returning a view, not when redirecting to another action. Basically it doesn't persist across separate requests. Try using TempData instead: TempData["Tag"] = post.SelectedTag.ToString(); and in the view: <p><strong>Tag: @TempData["Tag"]</strong></p> ...

Cannot get data using LINQ in MVC

c#,asp.net-mvc,linq,asp.net-mvc-4

Ensure term matches the case of the data. As all the data is loaded (.ToList() in the DAL), the .Where clause uses .Net comparison rather than SQL comparison: var vehicle = _service.GetAll().Where(c => c.Name.StartsWith(term, StringComparison.OrdinalIgnoreCase)... If, in the future, you want to change this to Contains, you can add an...

Redirect to different view when selecting dropdown then click button

javascript,jquery,asp.net-mvc-4

Try: $("#Reference").on("change", function() { if($("#Reference option:selected").text() == "SCHEME") window.location.href = '/YOURCONTROLLER/Index/' + YOUR_PARAMETERS; }); ...

How to bind anonymous type to viewModel in ASP.NET-MVC

c#,asp.net-mvc,asp.net-mvc-4

Dont leave your select query anonymus, just pass your select with viewModed like var v = (from pd in ge.Costs join od in ge.Services on pd.ServiceId equals od.ServiceId join ct in ge.ServiceTypes on pd.ServiceTypeId equals ct.ServiceTypeId where pd.ServiceTypeId.Equals(2) select new costViewModel() { CostId = pd.CostId, serviceName = od.serviceName, ServiceTypeValue =...

get roles attribute of controller in OnActionExecuting in mvc

c#,asp.net-mvc,asp.net-mvc-4,actionfilterattribute

You can use GetFilterAttributes method of ActionDescriptor or ControllerDescriptor: protected override void OnActionExecuting(ActionExecutingContext filterContext) { var filters = new List<FilterAttribute>(); filters.AddRange(filterContext.ActionDescriptor.GetFilterAttributes(false)); filters.AddRange(filterContext.ActionDescriptor.ControllerDescriptor.GetFilterAttributes(false)); var roles = filters.OfType<AuthorizeAttribute>().Select(f => f.Roles); ... } ...

Error while trying populate DropDownListFor from Database

c#,mysql,asp.net-mvc-4

In your GET method, your assign the SelectList used by @Html.DropDownList() using repository.ListData = repository.GetData(); however in the when you POST and return the view, you do not reassign the SelectList, hence Model.ListData is null. Your need to repeat the above line of code immediately before your call return View(inven);...

How to run javascript function in Razor MVC .net

javascript,asp.net-mvc,asp.net-mvc-4,razor

That sequence of numbers is not recognized by JavaScript. If you put it in quotes, it'll be treated like a string instead and be valid: var date = '@Model.Invoice.InvoiceDate'; Or, if you want a date object (and have a valid date for it!): var date = new Date('@Model.Invoice.InvoiceDate'); ...

Binding my view model to a view causes all check boxes to be checked

c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor

In your view, remove <input type="checkbox" value="" checked="checked"/> Allow Access Because of checked="checked", this will always print out a checked checkbox....

Convert ObjectResult to List

c#,asp.net-mvc,asp.net-mvc-4

If your ADDRESS_MASTER_Select_Distinct_Gaam method returns a list of strings, you can do this list=obj.Select(s=>new Member { AM_GAM_=x }).ToList(); But if your ADDRESS_MASTER_Select_Distinct_Gaam method is returning a list of some custom object where AM_GAM is a property of that custom class, you can do this list=obj.Select(s=>new Member { AM_GAM_=x.AM_GAM }).ToList(); ...

.Net MVC 4 using Windows Authentication - redirect unauthorized user

c#,asp.net-mvc,asp.net-mvc-4

For this you will need a Custom Authorization to handle the unauthorized situations yourself. You will need a method like this: [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class AuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute { protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext) { if (filterContext.HttpContext.Request.IsAuthenticated) { filterContext.Result = new...

Send a parameter from an action to a view

asp.net-mvc,asp.net-mvc-4

Finally I've found the solution. In the "get" action "SubirImagenes" I get the parameter and then, with a strong typed model, using a hidden field, I pass the parameter in the "post" action receiving it inside the model I pass as a parameter in that post action.

Use “Contains” to match part of string in lambda expression

c#,jquery,asp.net-mvc-4,lambda

I would search your initial items (before you made the into a list of TextValuePair) then you could do something like IEnumerable<Item> items = originalItemsList; switch (source) { case "1": // or whatever this should be items = items.Where(x => x.ItemNumber.IndexOf(data, StringComparison.InvariantCultureIgnoreCase) > -1); break; case "2": // or whatever...

Custom Data Annotation and MVC Helper

c#,asp.net-mvc,asp.net-mvc-4

You're gonna need to extend the HtmlHelper class with the following: public static MvcHtmlString HelpTextFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expr) { var memberExpr = expr.Body as MemberExpression; if (memberExpr != null) { var helpAttr = memberExpr.Member.GetCustomAttributes(false).OfType<HelpTextAttribute>().SingleOrDefault(); if (helpAttr != null) return new MvcHtmlString(@"<span class=""help"">" + helpAttr.Text + "</span>"); }...

A specified Include path is not valid. The EntityType '*Propiedad' does not declare a navigation property with the name 'Nombre'

c#,asp.net-mvc,entity-framework,asp.net-mvc-4,repository-pattern

Include is made to eagerly load navigation properties, meaning any property that is, in fact, another related entity. Since Nombre is a string, you do not need to include it: it is part of the entity that is returned from the database call. If Nombre were of a class representing...

MVC View trying to parse 2 strings in Details view

asp.net-mvc,asp.net-mvc-4,razor

You can use the ternary operator along with an explicit code nugget (wrap the code in ()) <h1>@(Model.unittype == "PRP" && Model.name =="TTO" ? "CISCO" : "---")</h1> ...

Add XElement dynamically using loop in MVC 4?

c#,xml,asp.net-mvc-4,for-loop

This is the complete code [HttpPost] public ActionResult SURV_Answer_Submit(List<AnswerQuestionViewModel> viewmodel, int Survey_ID, string Language) { if (ModelState.IsValid) { var query = from r in db.SURV_Question_Ext_Model.ToList() join s in db.SURV_Question_Model on r.Qext_Question_ID equals s.Question_ID where s.Question_Survey_ID == Survey_ID && r.Qext_Language == Language orderby s.Question_Position ascending select new { r, s };...

startIndex cannot be larger than length of string

c#,entity-framework,asp.net-mvc-4

You should have code in following way - string newFilenameExtension = Path.GetExtension("Sample".Trim()); string extn = string.Empty; if (!String.IsNullOrWhiteSpace(newFilenameExtension)) { extn = newFilenameExtension.Substring(1); } if(!String.IsNullOrWhiteSpace(extn)) { // Use extn here } ...

Jquery: Change contents of