如果你有两个简单的表单,可以使用以下方法:
你需要创建两个不同的局部视图。
@model CustomerInfoModel
@using (Ajax.BeginForm("CustomerInfo", "Customer", new AjaxOptions { HttpMethod = "Post", OnBegin = "InfoLoading", OnComplete = "InfoCompleted" }, new { id = "info", @class = "form-horizontal" }))
{
<input type="text" class="form-control" name="Name" id="Name" value="@Model.Name" />
<input type="email" class="form-control" name="Email" id="Email" value="@Model.Email" />
<button type="submit" id="save-info" class="btn-medium red">Save</button>
}
并且
@model CustomerPasswordChangeModel
@using (Ajax.BeginForm("CustomerPasswordChange", "Customer", new AjaxOptions { HttpMethod = "Post", OnBegin = "InfoLoading", OnComplete = "InfoCompleted" }, new { id = "change", @class = "form-horizontal" }))
{
<input type="password" class="form-control" name="OldPassword" id="OldPassword" value="" />
<input type="password" class="form-control" name="NewPassword" id="NewPassword" value="" />
<button type="submit" id="save-change" class="btn-medium red" autocomplete="off">Save</button>
}
在您的父视图中,
@Html.Partial("CustomerInfo", Model.CustomerInfo)
并且
@Html.Partial("CustomerPasswordChange", Model.CustomerPasswordChange)
在控制器中:
[HttpPost]
public ActionResult CustomerInfo([Bind(Include = "Name,Email")] CustomerInfoModel model)
{
if (ModelState.IsValid)
return new Json(new { success=true, message="Updated.", errors=null);
return new Json(new { success=false, message="", errors=getHtmlContent(ModelState.Values.SelectMany(v => v.Errors).ToList(), "ModelError"));
}
[HttpPost]
public ActionResult CustomerPasswordChange([Bind(Include = "OldPassword,NewPassword")] CustomerPasswordChangeModel model)
{
if (ModelState.IsValid)
return new Json(new { success=true, message="Updated.", errors=null);
return new Json(new { success=false, message="", errors=getHtmlContent(ModelState.Values.SelectMany(v => v.Errors).ToList(), "ModelError"));
}
这将会实现你想要的功能。
< p >< em >注意:getHtmlContent方法只是生成一个错误消息以在页面上显示。没有什么特别之处。如果需要,我可以分享它。