Reputation: 861
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.
Upvotes: 2
Views: 743
Reputation: 861
After reading the blog ARM has mentioned it seems the solution really depends on how one is loading the partial view. What eventually worked for me is to call __MVC_EnableClientValidation after view has been assigned to an element:
$.get('~/Product/New/', function(data) {
$("#dialog").html(data);
// extracted from MicrosoftMvcJQueryValidation.js
var allFormOptions = window.mvcClientValidationMetadata;
if (allFormOptions) {
while (allFormOptions.length > 0) {
var thisFormOptions = allFormOptions.pop();
__MVC_EnableClientValidation(thisFormOptions);
}
}
},'html');
Upvotes: 0
Reputation: 2385
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/
Upvotes: 2