rumi
rumi

Reputation: 3296

modelstate error 'The Id field is required' in mvc4 application

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

Upvotes: 0

Views: 3742

Answers (2)

Luis CR
Luis CR

Reputation: 1

I'm using MVC and have the same problem, so i check out all my create code and find that i wasn't send an empty model to the View at call time. The solution was simple; on the Create() action result, just add a line that creates a new ViewModel and set it as parameter to the View or Partial View return. Something like this:

public ActionResult Create(){
    ViewModel entity = new ViewModel();
    return PartialView(entity);
}

I hope that helps.

Upvotes: 0

matt_lethargic
matt_lethargic

Reputation: 2796

You're not passing the Id in, you need to add a hidden field that holds to Id otherwise how does the Id ever get passed into the posted model.

@Html.HiddenFor(x => x.Id)

Upvotes: 1

Related Questions