Reputation: 11615
Everything appears to work as expected except that when it returns back the Partial with the model that has NAME = "foo"
after it has inserted the object, it does not change the Name and PercentAlcohol text boxes with the values in the Model.
When I output @Model.Name
in the header of the partial by the validation messages it properly shows "foo"
. But the form still says whatever was in the textboxes when it was submitted.
<div id="createBeerForm">
@{Html.RenderPartial("CreatePartial", new BeerCreateModel());}
</div>
@{
AjaxOptions options = new AjaxOptions
{
HttpMethod = "Post",
UpdateTargetId = "createBeerForm",
InsertionMode = InsertionMode.Replace
};
}
@using (Ajax.BeginForm("Create", "Beer", null, options, new { @class = "form-stacked" }))
{
@Html.ValidationSummary(true, "You have errors. Fix them.")
@Html.LabelFor(m => m.Name)
<div>
@Html.TextBoxFor(m => m.Name, new { @class = "xlarge" })
@Html.ValidationMessageFor(m => m.Name)
</div>
@Html.LabelFor(m => m.PercentAlcohol)
<div>
@Html.TextBoxFor(m => m.PercentAlcohol, new { @class = "xlarge" })
@Html.ValidationMessageFor(m => m.PercentAlcohol)
</div>
<p>
<input type="submit" value="Create Beer" />
</p>
}
[HttpPost]
public ActionResult Create(BeerCreateModel model)
{
if (ModelState.IsValid)
{
//Add Beer to DB
return PartialView("CreatePartial", new BeerCreateModel { Name = "foo"});
}
else
{
return PartialView("CreatePartial", model);
}
}
Upvotes: 1
Views: 890
Reputation: 1039538
You must clear the modelstate if you intend to change values in your POST controller action. HTML helpers first look at the modelstate when binding and then at the model. So:
[HttpPost]
public ActionResult Create(BeerCreateModel model)
{
if (ModelState.IsValid)
{
//Add Beer to DB
// Here you are modifying the value of the Name parameter
// in your model. But this parameter is also in ModelState.
// So if you want this change to reflect on the subsequent view you
// need to either clear it from the modelstate
ModelState.Remove("Name");
return PartialView("CreatePartial", new BeerCreateModel { Name = "foo"});
}
else
{
return PartialView("CreatePartial", model);
}
}
Upvotes: 3