Reputation: 331
I've got a form that submits a model. The controller saves that model to the database, then creates a new model and returns an EditCreate view with that new model.
The problem I'm having is that the new model isn't being displayed. Instead the model that was just posted is shown. I follow it through the debugger to the view and see the values are new, but when the page displays, it shows all the old values that were just submitted.
Controller
[HttpPost]
public ActionResult AddProduct(MyEntityModel myModel)
{
// Save
if (myModel.ID != 0) {
Update(myModel);
} else {
Add(myModel);
}
ModelState.Clear(); // This fixed it
// Show page for new model
MyEntityModel newModel = new MyEntityModel();
newModel.ID = 0;
// Edit/Create page
ActionResult ret = EditCreateRow(newModel);
return ret;
}
Model
public partial class STM_AuditData
{
public int ID { get; set; }
public Nullable<System.DateTime> ServiceDate { get; set; }
public string Product { get; set; }
}
View
@Html.LabelFor(model => model.ServiceDate)
@Html.EditorFor(model => model.ServiceDate)
@Html.LabelFor(model => model.Product)
@Html.EditorFor(model => model.Product)
@Html.HiddenFor(model => model.AuditID)
What can I do to ensure the correct model shows? Thanks.
Here's the code for EditCreateRow
public ActionResult EditCreateRow(MyEntityModel row)
{
MyEntityModel.IntsToBools(ref row);
EditCreate_SetViewBagItems(row);
return View("~/Views/MyEntityModel/EditCreate.cshtml", row);
}
Upvotes: 1
Views: 478
Reputation: 91
The reason this is the case, is how the HtmlHelper works. When setting the value in the HTML-element, it has several options to get the value, using implementations of IValueProvider. You can check the default list at the aspnetwebstack. Compared to the better MVC frameworks out there, ASP.NET MVC is counter-intuitive.
If you add
ModelState.Clear()
before returning, I think you might have it solved.
Upvotes: 5