所有内容似乎都按预期工作,只是当它在插入对象后返回具有NAME = "foo"
的模型的Partial时,它不会使用模型中的值更改Name和PercentAlcohol文本框。
当我通过验证邮件在部分标题中输出@Model.Name
时,它会正确显示"foo"
。但表单仍然显示提交时文本框中的内容。
<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);
}
}
答案 0 :(得分:3)
如果要更改POST控制器操作中的值,则必须清除模型状态。 HTML帮助程序首先在绑定时查看模型状态,然后在模型中查看。所以:
[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);
}
}