PartialView和不显眼的客户端验证无法正常工作

mbe*_*Net 6 validation asp.net-mvc jquery

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

第一:当我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>
Run Code Online (Sandbox Code Playgroud)

我的控制器动作:

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);
}
Run Code Online (Sandbox Code Playgroud)

谢谢

mbe*_*Net 4

我终于让它发挥作用了。方法如下:

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

有辅助函数:

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;
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢