asp.net-mvc-5jquery-ui-dialogeditortemplates

Model validation inside dialog


I'm using MVC 5 for my app where a user can create a Foo that has zero to many Bars.

My create view for Foo calls HTML.EditorForModel() which loads an editor template for Foo. My Foo template has the HTML.BeginForm tag and a call to Html.EditorFor(model => Model.Bar) which loads an editor template for Bar that does not have the Form tag, but is using the BeginCollectionItem helper. So the end result is both the Foo and the Bar model are inside one Foo form.

When a user clicks the "Add new Bar" button an Ajax call appends the new Bar template and exposes it in a Jquery UI dialog - and after each append I'm reparsing the form so the validation picks up the new fields. On submission to the controller both the Foo and the Foo.Bars get correctly posted. Yay!

My issue is that in the dialog box the Validation isn't firing. If I drop the dialog and just expose the Bar fields in the DOM validation works great. I think this is because the Content in the dialog (the Bar template) doesn't include the Form tag. But if I add the form tag to the Bar template then the post to the controller fails.

Is it possible to get the model validation working inside the dialog while it's open in this scenario?


Solution

  • Answered my own question. By default the jQuery dialog appends just before the body tag so it's not inside the form. I used the "appendTo" option of the dialog to instead append it to the tag.