2010-11-15 101 views
6

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

1st:当我在我的动作中做一个return PartialView时,所有不显眼的属性都不会呈现。我发现了一种“非优雅”的方式,但是当我这样做时,客户端验证被破坏。从我的行动中返回后,即使我在更新的行上拨打jQuery.validator.unobtrusive.parse(),即使情况并非如此,$("form").valid()也总是返回正确。

第二:我希望我的渲染视图在服务器上呈现为一个字符串,因此我可以将其发送回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); 
} 

感谢

回答

4

我终于做它的工作。这就是:

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团队能够提供一种更简单的方式将视图呈现为字符串。

谢谢