Menu
  • HOME
  • TAGS

A property of model becomes null while posting

Tag: asp.net-mvc-4

I'm new to MVC. Now I'm trying with a simple demo of MVC that to print Customer's information to screen and update it, send back to database.

I have no idea why the Customer's ID becomes null while the others are fine.

I want to display Customer's ID to the screen but I don't want user to edit it to post to my database. I've been researching this for some hours now..

my code :

Customer.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace PeopleManagement.Models
{
    public class Customer
    {
        [Required]
        public string Id { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }

        public Customer()
        {

        }
        public Customer(string id, string name, int age)
        {
            Id = id;
            this.Name = name;
            this.Age = age;
        }
    }
}

Index.cshtml

@using System.Web.UI.WebControls
@using PeopleManagement.Models
@model IList<Customer>

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>First MVC Application</title>
        <link href="@Url.Content("~/Content/css/customized-table.css")" rel="stylesheet" type="text/css" />
    </head>

    <body style="max-width:100%; max-height:100%">

        <div id="pageTitle" style="text-align:center; color:red; font-size:24px; font-weight:bold;">Customer Management</div>
        @using (@Html.BeginForm("Index", "Home", FormMethod.Post))
        {
            <div id="tablePanel" style="padding-top: 15px">

                <table class="customized_table" border="1">
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Age</th>
                    </tr>

                    @{
                        for (var i = 0; i < Model.Count; i++)
                        {
                            <tr>
                                <td>
                                    @Html.HiddenFor(model => model[i].Name);
                                </td>
                                <td>
                                    @Html.TextBoxFor(model => model[i].Name, new {@style = "min-width:100%; text-align:center", @disable = "true"})
                                </td>
                                <td>
                                    @Html.TextBoxFor(model => model[i].Age)
                                </td>
                            </tr>
                        }
                    }
                </table>

            </div>

            <div>
                <p><input type="submit"/></p>
            </div>

        }

    </body>

</html>

<script>

</script>

HomeController.cs

using System.Collections.Generic;
using System.Web.Mvc;
using PeopleManagement.Models;

namespace PeopleManagement.Controllers
{
    public class HomeController : Controller
    {
        public List<Customer> CustomersList { get; private set; } = new List<Customer>(5);

        [HttpGet]
        public ActionResult Index()
        {
            CustomersList.Add(new Customer("ID_1", "Name_1", 1));
            CustomersList.Add(new Customer("ID_2", "Name_2", 2));
            CustomersList.Add(new Customer("ID_3", "Name_3", 3));

            ModelState.Clear();
            return View(CustomersList);
        }

        [HttpPost]
        public ActionResult Index(List<Customer> postbackCustomers)
        {
            if (!ModelState.IsValid)
                return View(CustomersList);

            CustomersList = postbackCustomers;

            return View(CustomersList);
        }
    }
}

Can anyone help ?

Best How To :

In MVC if you want to get some value back from view you have to have that value in the view first. It seems you have not inputted the Id in the view.

Change your view code like this,

for (var i = 0; i < Model.Count; i++)
            {
                <tr>
                    <td>
                        @Html.HiddenFor(model => model[i].Id)
                    </td>
                    <td>
                        @Html.TextBoxFor(model => model[i].Name, new { @style = "min-width:100%; text-align:center", @disable = "true" })
                    </td>
                    <td>
                        @Html.TextBoxFor(model => model[i].Age)
                    </td>
                </tr>
            }

Hope this helps!!

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...

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"...

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)...

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 ...

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...

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; } }...

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....

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...

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");

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. ...

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...

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...

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(); ...

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...

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....

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 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.

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...

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...

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,...

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 };...

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); } ...

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> { } ...

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 =...

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...

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; }...

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> } ...

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 - 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"> ...

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...

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...

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...

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...

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....

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 ...

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>"); }...

Angularjs ng-show doesn't work with Viewbag

angularjs,asp.net-mvc-4

Try this: <div ng-show="'@(ViewBag.AllowExport)'"> <a href="JavaScript:void(0);">Export</a> </div> ...

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;...

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...

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...

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...

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...

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); } ...

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); ... } ...

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 } ...

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?

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> ...

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.

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....