ncabral
ncabral

Reputation: 2522

MVC3 Ajax Form Validation with Partial View not Working

I have a strange problem where the unobtrusive validations inside a partial view (which is being rendered by a Ajax.ActionLink) does not work.

This is the Partial View:

@model MyWeb.Models.PersonSkill
@using (Ajax.BeginForm("EditSkill", null, new AjaxOptions { UpdateTargetId = "skills" }, new { id = "EditSkillForm" }))
{
@Html.HiddenFor(model => model.Id)
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Name)
    @Html.ValidationMessageFor(model => model.Name)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.YearsOfExperience)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.YearsOfExperience)
    @Html.ValidationMessageFor(model => model.YearsOfExperience)
</div>

<p>
    <input type="submit" value="Save"/>
</p>
}

And this is called by:

@Ajax.ActionLink("Edit", "LoadEditSkill", new { id = item.Id }, new AjaxOptions() { UpdateTargetId = "editSkillDialog" }, new { @class = "editSkill" })

The view is rendered fine. It posts back data to the server, but it just doesn't validate.

Upvotes: 4

Views: 4544

Answers (2)

ncabral
ncabral

Reputation: 2522

Many thanks to Joe Tuskan for pointing me at the right direction.

I fixed the issue by adding an OnSuccess subscriber to my call:

@Ajax.ActionLink("Edit", "LoadEditSkill", new { id = item.Id }, new AjaxOptions() { UpdateTargetId = "editSkillDialog", OnSuccess = "onSuccess" }, new { @class = "editSkill" })

and adding calling parse() like explained here:

var onSuccess = function () {
    // enable unobtrusive validation for the contents
    // that was injected into the <div id="result"></div> node
    $.validator.unobtrusive.parse($("#editSkillDialog"));
};

Upvotes: 5

Freeman
Freeman

Reputation: 5801

Always make sure you included the necessary references to

jquery.validate.min.js and jquery.validate.unobtrusive.min.js and of course the main jquery library, this is usually the most common problem, and as i can see in your cshtml they are not present in your page either.

Upvotes: 1

Related Questions