MVC2 ModelBinder not binding to 'id' property of model
I have a model called Project, that has the following properties (simplified for brevity's sake).
[DataContract(IsReference = true)]
public class Project
{
[Key]
[DataMember]
public int id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public DateTime CreatedDate { get; set; }
}
The model is also a datacontract for a WCF service that uses Entity Framework 4 to query a datastore. The code for the model is generated from a template that automatically generates a CRUD service layer against the Entity Framework Model.
Now, my MVC2 application has a view containing a form to edit the fields. The controllers Edit action accepts the entire model as an argument upon POST.
[HttpPost]
public ActionResult Edit(Project project)
{
var context = new ServiceContext();
try
{
if (ModelState.IsValid)
{
project = context.UpdateProject(project);
return RedirectToAction("Index");
}
}
catch
{
ModelState.AddModelError("", "Could not save project");
}
return View(project);
}
Now, my problem is that when the form is posted to the controller, the Project model has all its fields correctly populated except for the 'id' property, which defaults to 0.
I've done some digging and pleaded with Uncle Google for answers, but the closest fix I could get was to add the following to the model's class,
[Bind(Include="id")]
which works fine, but ONLY populates the 'id' property, meaning that I would have to explicitly specify each property to be included in the model binding. Obviously, this can get nasty, especially since the model itself has many more properties than the one's I've shown above.
Is there any other way to get this working?
Gut feel is that the [Key] attribute has something to do with it, but 开发者_Go百科I haven't been able to figure anything out.
The form has a hidden input for the 'id' property.
<%: Html.HiddenFor(model => model.id)%>
Try Adding additional hidden field for ID like <%: Html.HiddenFor(model => model.Id) %>
I think I have found the solution.
My model also has some complex properties which map to related tables in my entity framework model. Now, since I'm using the Self-Tracking Entities T4 templates to generate my service layer, it has some additional logic when it comes to mapping values to entities. In this case, one of the complex properties is a class called Status which looks like this:
public class Status
{
public int ProjectId { get; set; }
public int StatusId { get; set ; }
}
The ProjectId is a foreign key to the Project table in my datastore. I noticed that the ProjectId field was also set to 0 during model binding.
When I added the following to my view
<%: Html.HiddenFor(model => model.Status.ProjectId) %>
both fields had the correct value posted to the controller.
Problem solved :)
Thanks swapneel for your thoughts on the matter.
精彩评论