I m using a viewmodel on my create view. Every thing works but on form post via jquery I m getting The Id field is required ModelState error. I have seen some solutions regarding adding [Bind(Exclude = "Id")] annotation in the model class but then when I call the same action method on the Update model it never binds the Id of the model and inserts a new record in db.
My viewmodel looks like
public class MemberSiteContactModel { public int Id { get; set; } [Display(Name = "Name")] [Required(ErrorMessage = "Name is required")] public string Name { get; set; } // More items } My partial view looks like
@model MemberSiteContactModel <tr class="highlight"> <td class="col-sm-1">@Html.TextBoxFor(x => x.Name, new { @class = "name" })</td> <td class="col-sm-2">@Html.TextBoxFor(x => x.ContactNo, new { @class = "contactNo" })</td> <td class="col-sm-1"><input type="button" class="btn btn-xs btn-success contactSaveRow" value="Save" /></td> <td class="col-sm-1"><input type="button" class="btn btn-xs btn-danger contactDeleteRow" value="Remove" name="btnRemoveContact" /></td> </tr> My controller looks like
[HttpPost] [ValidateAntiForgeryToken] public ActionResult SaveSiteContact(MemberSiteContactModel memberSiteContactModel) { if (ModelState.IsValid) { //processing } } I have also created a sample application to replicate the behavior
public class CityModel { public int Id { get; set; } [Display(Name = "City")] [Required(ErrorMessage = "City is required")] public string City { get; set; } } public ActionResult Contact() { return View(); } @model WebApplication3.Models.CityModel @using (@Html.BeginForm("SaveCity", "Home", FormMethod.Post)) { @Html.HiddenFor(x => x.Id) @Html.TextBoxFor(x => x.City) <input type="submit" value="Submit" /> } [HttpPost] public ActionResult SaveCity(CityModel cityModel) { if (ModelState.IsValid) { } return null; }
0but model state still shows the same error i.e. The Id field is required