提问人:Jason 提问时间:12/15/2011 更新时间:12/15/2011 访问量:888
MVC3 不显眼的 Ajax - 不反映模型的部分视图
MVC3 Unobtrusive Ajax - Partial View Not Reflecting Model
问:
一切似乎都按预期工作,只是当它返回带有模型的 Partial 时,它不会使用模型中的值更改 Name 和 PercentAlcohol 文本框。NAME = "foo"
当我通过验证消息在部分的标头中输出时,它正确地显示 .但是,该表单仍然显示提交时文本框中的任何内容。@Model.Name
"foo"
[HTML全文]
<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);
}
}
答:
3赞
Darin Dimitrov
12/15/2011
#1
如果要更改 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);
}
}
评论
0赞
Jason
12/15/2011
仅仅执行 Model.Clear() 有什么副作用吗?这个想法是表单将采用模态,如果成功,我想加载一个空白并隐藏模态。
1赞
Darin Dimitrov
12/16/2011
@Blankasaurus,是的,您正在擦除整个 ModelState 以及任何验证错误。如果你不在乎这个,那么你可以做到。
评论