[英]Ajax.BeginForm Displays Partial as a New Page
我在“主页/索引”页面上呈现了部分视图。 它是一个简短的表格,带有用于验证的viewmodel和批注。
它调用控制器,并在发生故障时(因为我未在其中键入任何内容并且我的视图模型中有[Required]标签),因此它将部分视图重新呈现为新页面。
我的问题是我是否必须自己返回JSON并标记表单无效字段? 还是可以使用正常的返回PartialView(model)?
我包括:
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<%using (Ajax.BeginForm("Coupon", new AjaxOptions { HttpMethod = "Post", OnSuccess = "CouponSubmitted" }))
{ %>
<div style="top: 337px; position: relative;">
<div style="margin-left: 51px; float: left;">
<%= Html.TextBoxFor(p => p.Name, new { Style = "width:130px;" })%>
<%= Html.ValidationMessageFor(p => p.Name)%>
</div>
<div style="float: left; margin-left: 44px;">
<%= Html.TextBoxFor(p => p.PhoneNumber, new { Style = "width:130px;" })%>
<%= Html.ValidationMessageFor(p => p.PhoneNumber)%>
</div>
<div style="float: left; margin-left: 34px; width: 80px;">
<%= Html.TextBoxFor(p=>p.Extension, new { Style = "width:70px;" })%>
<%= Html.ValidationMessageFor(p => p.Extension)%>
</div>
<div style="clear: both;">
</div>
</div>
<div style="top: 354px; position: relative;">
<div style="margin-left: 51px; float: left;">
<%= Html.TextBoxFor(p => p.Email, new { Style = "width:130px;" })%>
<%= Html.ValidationMessageFor(p => p.Email)%>
</div>
<div style="float: left; margin-left: 44px;">
<%= Html.TextBoxFor(p=>p.CellNumber,new{Style="width:130px;"})%>
<%= Html.ValidationMessageFor(p => p.CellNumber)%>
</div>
<input style="float: left; margin-left: 34px;" type="submit" value="Submit" />
<div style="clear: both;">
</div>
</div>
<%} %>
[HttpPost]
public ActionResult Coupon(Web.ViewModels.CouponViewModel model)
{
if (ModelState.IsValid)
{
//Submit info
Response.Cookies["ShowCoupon"].Value = "false";
Response.Cookies["ShowCoupon"].Expires = DateTime.Now.AddMinutes(2);
return Json(new {success=true});
}
else
{
return PartialView(model);
}
}
我看到有两点需要改进。
1)尝试将您的“提交”按钮替换为Ajax.ActionLink
。 成为您的“提交”按钮的原因是导致发回完整邮件,而不是Ajax请求。
2)发生完整的回发后,如果发生故障,您将返回完整的部分视图。 这导致您的主窗体消失,仅保留部分视图。
要像我前面提到的那样整理这些东西,请用Ajax.ActionLink替换Submit按钮,然后在模型出现故障时,不要返回PartialView。 在成功流程中返回Json。
高温超导
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.