Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC 3 Unobtrusive validation not working on Partial View

I've setup a partial view which houses its own form tag, like so:

<tr>
    @using (Html.BeginForm("Create"))
 {
        <td>
            @Html.TextBoxFor(model => model.Date)
            @Html.ValidationMessageFor(model => model.Date)
        </td>
        <td>
            @Html.TextBoxFor(model => model.Amount)
            @Html.ValidationMessageFor(model => model.Amount)
        </td>
        <td>
            @Html.TextBoxFor(model => model.Tags)
            @Html.ValidationMessageFor(model => model.Tags)
        </td>
        <td>
            @Html.EnumDropDownListFor(model => model.Type)
        </td>
        <td>
            <input type="submit" value="Add" />
            @Html.ValidationSummary(true)
        </td>
 }
</tr>

I render it on a page using @Html.Action("Create") (It's part of a table, hence the <tr> tags.

For some odd reason my clientside validation isn't working, and I first see the errors upon posting.

Is there something special about partial views and clientside validation ?

I have included the following scripts:

<script src="/Scripts/jquery.1.5.1.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>

EDIT

I just tried tossing this script onto the page:

jQuery('form').submit(function ()
{
    alert(jQuery(this).valid());
});

It alerts 'true', so the clientside validation script is definately there, and for some reason it's not checking the fields in question :-/

EDIT 2

I've uploaded the entire source code for the page (the HTML + JS) to pastebin: http://pastebin.com/GvqLW495

like image 592
Steffen Avatar asked Mar 14 '11 17:03

Steffen


1 Answers

Edit:

I just realized, looking at your code, that you're using jQuery 1.5.1 with the (I'm assuming) .NET provided jQuery.validate. Unfortunately, those two do not work together yet. You'll have to head to here to grab a version that works with the latest jQuery (you'll need to use 1.4.4). If that doesn't work, I would still recommend checking out the solution below.


I had a similar problem (although I'm not sure it's the exact same problem). I wrote about the solution in this blog post. Unfortunately, I can't be sure you're having the same exact problem, but it's worth a shot.

Basically, it boiled down to the fact that I had to call this line after loading my PartialViews (although I was loading them via AJAX which is what I think caused the problem):

$.validator.unobtrusive.parse($("#validation"));

See the blog post for more detail. Hopefully it helps you out.

like image 86
JasCav Avatar answered Oct 17 '22 04:10

JasCav