【问题标题】:PartialView and unobtrusive client validation not workingPartialView 和不显眼的客户端验证不起作用
【发布时间】:2011-05-10 10:04:52
【问题描述】:

我目前正在使用 ASP.NET MVC3 RC,并且正在使用 Brad Wilson 在his blog 上描述的不显眼的 JQuery 验证。它工作得很好,但是当我将表单(在 Ajax 中)发送到服务器时,如果我的模型状态无效,我会进行一些服务器端验证并返回同一行(包含在部分视图中)。 2个问题:

1st:当我在操作中执行return PartialView 时,不会呈现所有不显眼的属性。我找到了一种“非优雅”的方法,但是当我这样做时,客户端验证被破坏了。从我的操作返回后,即使我在更新的行上调用 jQuery.validator.unobtrusive.parse(),$("form").valid() 总是返回 true,即使不是这样。

第二:我希望我的渲染视图在服务器上呈现为字符串,以便我可以将它发送回 JsonResult(例如:myJSonResult.html=RenderPartialToString("partialName",model))。

有参考,有我的看法(editInvitation):

<td>
    <%= Html.HiddenFor(x=>x.ID,new{id="ID"}) %>
    <%= Html.HiddenFor(x=>x.GroupID,new{id="GroupID"})  %>
    <%: Html.TextBoxFor(x => x.Name, new { id = "Name" })%><%:Html.ValidationMessageFor(x=>x.Name) %>
</td>
<td>
    <%: Html.TextBoxFor(x => x.Email, new { id = "Email" })%>  <%:Html.ValidationMessageFor(x=>x.Email) %>
</td>
<td>
    <%: Model.Status.ToFriendlyName()%>
</td>
<td>
  <%= InvitationsViewModel.RenderActions(Model, Html, InvitationsViewModel.CreateRowID(Model.ID))%>
</td>

还有我的控制器操作:

if (TryUpdateModel(invitation))
{
    validModel = true;
    //Other stuff
}
if (Request.IsAjaxRequest())
{
     //TODO : I return a partial view but I would prefer to return a JSonResult with the rendered view as a string in an Property of my JSon result
     return PartialView(validModel ? "DisplayInvitation" : "EditInvitation", invitation);
}

谢谢

【问题讨论】:

    标签: jquery asp.net-mvc validation


    【解决方案1】:

    我终于成功了。就是这样:

    HtmlHelper helper = GetHelper();
    MvcHtmlString partialView = helper.Partial("myView" , model);
    var result = new { success = ModelState.IsValid, html = partialView.ToString() };
    return Json(result);
    

    还有辅助函数:

    protected HtmlHelper GetHelper()
    {
        return GetHelper(string.Empty);
    }
    protected HtmlHelper GetHelper(string formID)
    {
        HtmlHelper helper = new HtmlHelper(getViewContext(formID), new ViewPage { ViewData = this.ViewData });
        helper.EnableClientValidation(isClientValidationEnabled());
        helper.EnableUnobtrusiveJavaScript(isUnobtrusiveJavascriptEnabled());
        return helper;
    }
    private ViewContext getViewContext(string formID)
    {
        var vc = new ViewContext(this.ControllerContext, new WebFormView(this.ControllerContext, "~/Views/Home/Index.aspx"), this.ViewData, new TempDataDictionary(), new System.IO.StringWriter());
        vc.UnobtrusiveJavaScriptEnabled = isUnobtrusiveJavascriptEnabled();
        vc.ClientValidationEnabled = isClientValidationEnabled();
        vc.FormContext = new FormContext { FormId = formID };
        return vc;
    }
    

    我不确定这是不是最好的方法,但它对我有用。让我们希望 ASP.NET MVC 团队能够提供一种更简单的方法来将视图呈现为字符串。

    谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多