Simon Williams
Simon Williams

Reputation: 1046

Client side validation not working with ASP.Net MVC Razor and Ajax form

I am displaying a partial view inside a JQuery UI dialog. The partial view contains fields that include Html.ValidationMessageFor entries and the form itself has a Html.ValidationSummary. I can't seem to get client side validation to work at all. I am expecting to see error messages if I leave a field empty and tab to another field. I have been able to see the validation messages if I include this line upon successful loading of the partial view...

$.validator.unobtrusive.parse('#theForm');

but that is only when I submit the ajax form, not before.

jquery to load the partial view in a jquery ui dialog...

$('#theForm').load('/Company/Edit', function (response, status, xhr)
        {
            if (status != "success")
                $('#theForm').html('failed to load details')
            else {
                $.validator.unobtrusive.parse('#theForm');
                $('#theForm').dialog({ title: title, show: 'blind', hide: 'blind', width: '1000px' });
                $('#theForm').dialog('open');
            }
          });

Partial View...

    @model CompanyDetails

    @using (Ajax.BeginForm("Save", "Company", new AjaxOptions() { HttpMethod="Post", OnSuccess="closeForm" }, new {@id = "companyDetailsForm"}))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary() 
        <fieldset>
            <legend>Company Details Form</legend>
            <ol>
                <li>
                    @Html.LabelFor(c => c.Name)
                    @Html.TextBoxFor(c => c.Name)
                    @Html.ValidationMessageFor(c => c.Name)
                </li>
                <li>
                    <input type="submit" value="Save" />
                </li>
            </ol>
        </fieldset>
}

Here is the model clas....

public class CompanyDetails
{
    [Required]
    [Display(Name = "Company Name")]
    public string Name { get; set; }
}

And I have this in my web.config...

<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="ClientValidationEnabled" value="true"/>

I have the following javascript files included..

Can anyone spot what I have done wrong?

Upvotes: 2

Views: 4656

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

but that is only when I submit the ajax form, not before.

That's how unobtrusive javascript validation works. If you leave a field blank and tab out from it, validation won't trigger until you attempt to submit the form.

Upvotes: 4

Related Questions