PartialView and unobtrusive client validation not working

后端 未结 1 1907
深忆病人
深忆病人 2021-01-05 12:34

I\'m currently using ASP.NET MVC3 RC and I\'m using the unobtrusive JQuery validations as described by Brad Wilson on his blog. It works great but when I send my form (in Aj

相关标签:
1条回答
  • 2021-01-05 13:30

    I finally make it worked. This is how :

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

    There's the helper functions:

    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;
    }
    

    I'm not sure it's the best way to do it but it worked for me. Let's hope the ASP.NET MVC team would provide an easier way to render a view as a string.

    Thanks

    0 讨论(0)
提交回复
热议问题