Client form validation not working with modal dialog in MVC
Asked Answered
V

5

19

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.

Villa answered 27/5, 2014 at 12:45 Comment(0)
L
54

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");
Leporide answered 27/5, 2014 at 12:54 Comment(8)
thanks cadrell0 .. where do i put $.validator.unobtrusive.parse?Villa
Yap this does work perfectly. Third option: Load the jquery, validation and unobtrusive libraries in the dialog page, if the (separate) page is being loaded by a dialog.Annulment
You got an upvote from me, that fixed it for me too. Thanks again.Leprosarium
I cannot figure this out! I have a form inside a form. Should the forms be separate?Contradance
FML wasted like 6 months not knowing this.Educable
THE ANSWER IS COPIED FROM itorian.com/2015/05/mvc-client-side-validation-not-working.htmlElysian
The answer was posted a year before the linked blog post. It's probably the other way around.Leporide
@Leporide Please where can I put $.validator.unobtrusive.parse("#id-of-the-form");Wherein
T
12

If you are loading the dialog dynamically just register the unobtrusive validation in the containing element's change event:

$('#modal-container').change(
    function() {
        $.validator.unobtrusive.parse("#your-form-id");
});
Team answered 15/9, 2016 at 3:22 Comment(1)
No. The accepted answer says "Include the form on the page during the initial load. " My suggestion is to add the change event listener to the element that will contain the dialog when it is Dynamically injected. This is a better fit if you are dynamically injecting a form from a partial view, which is what the question is about.Team
H
1

In partialview of create page -> modal-header, model-body, modal-footer and javascript code in the <script>your code </script> - don't put <script>your code</script> in @section Scripts{} and it will work.

Huberman answered 12/7, 2016 at 20:0 Comment(0)
E
1

Just add the following scripts in your Create form view:

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" 
    type="text/javascript">
</script>

<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" 
    type="text/javascript">
</script>
Eboat answered 9/3, 2018 at 10:12 Comment(0)
E
0

Adding a new comment to share a more modern solution:

Use BundleConfig.cs in the App_Start folder of your MVC project.

namespace MySolution
{
    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new StyleBundle("~/Content/css").Include(
                "~/Content/Site.min.css",
                "~/Content/bootstrap.min.css"));

            bundles.Add(new ScriptBundle("~/Scripts/js").Include(
                "~/Scripts/jquery-3.3.1.min.js",
                "~/Scripts/jquery.validate.min.js",
                "~/Scripts/jquery.validate.unobtrusive.min.js"));
        }
    }
}
Electrostatic answered 28/8, 2020 at 18:44 Comment(1)
how this is helping on achieving the "modal" validation?Effieeffigy

© 2022 - 2024 — McMap. All rights reserved.