I have the following actions in my controller. The first (top) Edit works fine and serves the correct values. However, in the second one, i.e. the ‘return’ Edit, every property of model is at default value, i.e. null for ref types and zero for value types. I have examined the HTTP post data and it has all the properties correctly named and with correct values. What could be wrong?
Controller excerpt:
[Authorize(Order = 0, Roles = "Requester, Controller")]
public ActionResult Edit(int id)
{
JobCardViewData viewData = ViewDataFactory.CreateBaseViewData<JobCardViewData>("Installation Details");
viewData.JobCard = new JobCardService().GetById(id);
return View(viewData);
}
[HttpPost]
public ActionResult Edit(JobCard model)
{
try
{
new JobCardService().Update(model);
var x = RedirectToAction("Index");
return RedirectToAction("Index");
}
catch (Exception)
{
return RedirectToAction("Edit", new {id = model.InstallationNumber});
}
}
View excerpt:
<div class="editor-label">
<%: Html.LabelFor(model => model.JobCard.Name) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.JobCard.Name) %>
<%: Html.ValidationMessageFor(model => model.JobCard.Name) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.JobCard.Surname) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.JobCard.Surname) %>
<%: Html.ValidationMessageFor(model => model.JobCard.Surname) %>
</div>
Refer to this answer from Phil Using ViewModel Pattern with MVC 2 Strongly Typed HTML Helpers
When you use the strongly typed helpers against the type, the helpers create form fields assuming that’s the type you’re posting to. When the types don’t match up, there’s a problem.
In this case, the type being posted to (
JobCard) is different to the type the view originally was created against(JobCardViewData).Try changing the method signature to the ffg and I am almost certain the
JobCardvalues will be populated within the model.Phil presents two approaches which can be used to resolve this.