Client form validation not working with modal dialog in MVC

lawphotog picture lawphotog · May 27, 2014 · Viewed 23.9k times · Source

I am changing a create form to become a modal dialog and jquery Unobtrusive validation stops working and don't know how to fix it.

Index.cshtml has a link to trigger a modal dialog.

<a href="#" id="createCustomer">Create</a>
@section scripts{
<script type="text/javascript">
$('#createCustomer').on('click', function () {
        $.get('/Customer/Create', function (data) {
            $('#modalContainer').html(data);
            $('#myModal').modal({});
        });
    });

Create.cshtml is a partial view.

@model Demo.Web.Models.CustomerVm
@using (Html.BeginForm("Create", "Customer", FormMethod.Post, new { @id="createForm" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Customer</h4>
        <hr />
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")        
}

On the controller there is an actionmethod which returns a partial view for create form.

public ActionResult Create()
    {
        return PartialView("Create");
    }

view modal

public class CustomerVm
{
    [Required]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }        
}

before i changed it to be a modal dialog .. everything was working but now i don't know how to fix it. How can i make validation work with dialog? Obviously, I don't want to rewrite validation rules on client script .. i want to get it working from view model .. thanks.

Answer

cadrell0 picture cadrell0 · May 27, 2014

Because the form is not added to the page when the page loads, the unobtrusive validation will not pick it up. There are two ways to fix this.

  1. Include the form on the page during the initial load. This will cause the form to be recognized and validation will occur. You can throw the partial view in a hidden div. Then your JavaScript will just show the modal dialog.
  2. Manually register the form with the unobtrusive validation after adding it to the page. Something like $.validator.unobtrusive.parse("#id-of-the-form");