asp.net-mvcasp.net-mvc-2-validation

Client side validation script is not generated for partial views fetched using AJAX


I am trying to setup client side validation using MicrosoftMvcJQueryValidation to work with ajax submitted forms. It works perfectly fine if the partial view is rendered directly from a view. However when I try to fetch it over XHR, for example to show it in a JQuery Dialog, client validation javascript is not generated for the output html. Any ideas?

Working code - partial view is rendered using Html.RenderPartial:

View:

<%@ Page Title="" Language="C#"  Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
 <% Html.RenderPartial("New"); %>
</asp:Content>

Partial View:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Product>" %>
<% Html.EnableClientValidation();%> 
<% Html.BeginForm();%>
  <%= Html.EditField(m => m.price)%>
  <%= Html.ValidationMessageFor(m => m.price)%>
<% Html.EndForm();%>

Not working code - partial view is fetched with JQuery load() function.

View:

<%@ Page Title="" Language="C#"  Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

 ....

 $("#dialog").load('~/Product/New/');
 $("#dialog").dialog("open");

 ....

 <div id="dialog" title=""></div>
</asp:Content>

Relevant controller action:

public PartialViewResult New(int id)
{
  return PartialView(service.GetProduct());
}

Thanks.


Solution

  • This will happen for all partial views which return JavaScript inserted into the DOM via AJAX. The problem is that the JavaScript returned with the partial view is not executed/interpreted when it is inserted into the document.

    Unfortunately, because what you are dealing with is generated JavaScript I can explain why you are experiencing the problem but I'm at a loss for a solution. Were this a function you wrote I'd suggest adding it to the OnComplete. All I can offer is that this is a JavaScript limitation and to start looking there.

    BTW: this looks promising http://adammcraventech.wordpress.com/2010/06/11/asp-net-mvc2-ajax-executing-dynamically-loaded-javascript/