[英]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.