代码之家  ›  专栏  ›  技术社区  ›  Jason

ajax.begininform将部分显示为新页面

  •  1
  • Jason  · 技术社区  · 15 年前

    我有一个在主页/索引页上呈现的部分视图。它是一个简短的表单,带有用于验证的ViewModel和批注。

    它调用控制器,当失败时(因为我没有在视图模型中键入任何内容,并且我的视图模型中有[必需的]标记),它会将局部视图重新呈现为一个新页面。

    我的问题是,我是否需要返回JSON并自己标记表单中的无效字段?或者我可以使用普通的返回部分视图(模型)?

    我包括:

        <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 回复  |  直到 15 年前
        1
  •  1
  •   Pradeep    15 年前

    我可以看到两点需要改进。

    1)尝试将“提交”按钮替换为 Ajax.ActionLink . “提交”按钮的原因是导致完全回发而不是Ajax请求。

    2)一旦发生完整的回发,您将返回完整的部分视图,以防失败。这会导致你的主形态消失,只留下部分的视图。

    如前所述,要解决这些问题,请将Submit按钮替换为Ajax.ActionLink,然后当模型出现故障时,不要返回partialView。像在成功流程中那样返回JSON。

    高温高压