Travis J
Travis J

Reputation: 82357

Why does validation break on partial view?

This validation should work, but the post fires right past it if there are no selected values in the dropdown. When moved to another non-partial the validation works just fine. Edited for brevity.

ViewModel:

public class BuilderVM
{
    [Display(Name = "Select A Task")]
    [Required]
    public int? TaskId { get; set; }
    public GenericSelectList Tasks { get; set; }
}

Parent View (the partial view is rendered at the bottom of this page after a post. as you may have noticed, the ajax options dictate that the partial view will be rendered in div id="MoveOn"):

@{
 ViewBag.Title = "Builder";
 AjaxOptions ajaxOpts = new AjaxOptions
 {
    LoadingElementDuration = 2,
    LoadingElementId = "removeChoice",
    UpdateTargetId = "MoveOn"
 };
}
<div id="removeChoice">
@using (Ajax.BeginForm("Selected", ajaxOpts))
{
<fieldset>
    <div>
     //Data For Submission (This data validates perfectly before post)
    </div>
    <p><input type="submit" value="Go" /></p>
</fieldset>
}
</div>
<div id="MoveOn"></div>

Partial View (rendered after a post from parent view):

@model namespace.BuilderVM
@{
 AjaxOptions ajaxOpts = new AjaxOptions
  {
    UpdateTargetId = "Entry",
    LoadingElementDuration = 2,
    LoadingElementId = "RemoveEntry"
  };
}

<div id="RemoveEntry">
<h2>Details</h2>
@using (Ajax.BeginForm("Data", ajaxOpts))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Data</legend>
<div>
    <span class="label">@Html.LabelFor(model => model.TaskId)</span>
    <span class="content">
    @Html.DropDownListFor(
        model => model.TaskId,
        new SelectList(
            Model.Tasks.Values,
            "Id",
            "DisplayFields",
            Model.Tasks.StartValue
        ),
        Model.Tasks.Message
    )
    </span>@Html.ValidationMessageFor(model => model.TaskId)
</div>
<p><input type="submit" value="Add Work Completed Data" /></p>
</fieldset>
}
</div>
<div id="Entry"></div>

Although the dropdownlistfor is bound to model.TaskId which is annotated with [Required] when the post button is clicked (input type="submit") and there is no value selected in the dropdownlist the post goes through instead of stopping and appending the validation message. I am not sure what to do to fix this, as it works just fine when copy pasted to a regular view. Why wont the partial view validation work?

Upvotes: 1

Views: 2624

Answers (1)

Florian Rappl
Florian Rappl

Reputation: 3189

The problem is that the validator just loads in the beginning (with $(document).ready()). What you can do is the following (insert in the partial view):

    <script>
        $(function() {
            $.validator.unobtrusive.parse('.Content');
        });
    </script>

From the given information I assume this is your problem. Hope this helps you.

Upvotes: 3

Related Questions