Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC5 Bootstrap 3 Modal Form not validating client-side and is posting back to page

I have an MVC5 application that I am just starting to do some Ajax on. I have a page with a button which when clicked opens up a Bootstrap modal with a form from another action. However, when that modal form is submitted, the jquery unobtrusive validation is not being called and the page redirects to a partial view on a blank page, instead of inside the modal dialog.

So, 1: How can I get jquery validation to work inside the modal, and 2: How can I make the form not refresh the page, but reload the returned view into the modal? and 3: I'm confused by how Ajax.BeginForm is supposed to work as I would assume it wouldn't create a page refresh.

Here's the page which contains a button to load the modal:

@using Plus.ViewModels
@model UserViewModel
@{
    ViewBag.Title = "Personal Details";
}
@using (Html.BeginForm(null, null, FormMethod.Post, new { @class = "form-horizontal" }))
{
    @Html.AntiForgeryToken()
// A separate form here

<div class="form-actions">
    <button class="btn btn-primary" type="submit">
      <i class="fa fa-save"></i>
       Save
    </button> |

 <a class="btn btn-primary" href="@Url.Action("ChangePassword", "Manage", new object{})" data-toggle="modal" data-target="#myModal">Change Password</a>

</div>
}


<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
    <div class="modal-dialog">
        <div class="modal-content">
        </div>
    </div>
</div>

@section Scripts {
    <script type="text/javascript">
        $('#myModal').on('shown.bs.modal', function () {
            jQuery.validator.unobtrusive.parse($(this));
        })
    </script>   
}

The View that contains the form I want to submit inside the modal dialog:

@model Plus.ViewModels.ChangePasswordViewModel
@{
    ViewBag.Title = "Change Password";
    Layout = "";

    AjaxOptions options = new AjaxOptions();
    options.HttpMethod = "POST";
    options.Url = Url.Action("ChangePassword", "Manage");
    options.UpdateTargetId = "modalForm";
    options.InsertionMode = InsertionMode.Replace;
}

@using (Ajax.BeginForm("ChangePassword", "Manage", null, options, new { @class = "form-horizontal", role = "form" }))
{
    <div id="modalForm">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h4 class="modal-title" id="myModalLabel">Change Password</h4>
        </div>
        <div class="modal-body">

            @Html.AntiForgeryToken()
            @Html.ValidationSummary("", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(m => m.OldPassword, new { @class = "col-md-6 control-label" })
                <div class="col-md-6">
                    @Html.PasswordFor(m => m.OldPassword, new { @class = "form-control" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(m => m.NewPassword, new { @class = "col-md-6 control-label" })
                <div class="col-md-6">
                    @Html.PasswordFor(m => m.NewPassword, new { @class = "form-control" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-6 control-label" })
                <div class="col-md-6">
                    @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
                </div>
            </div>

        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">Change Password</button>
        </div>
    </div>
}

The Controller for the actions:

public ActionResult ChangePassword()
{
    ChangePasswordViewModel cpvm = new ChangePasswordViewModel();
    return PartialView(cpvm);
}

//
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model)
{
    if (!ModelState.IsValid)
    {
        return PartialView(model);
    }
    var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
    if (result.Succeeded)
    {
        return Json(new { success = true });
    }
    // Failed
    AddErrors(result);
    return PartialView(model);
}
like image 509
Rhys Stephens Avatar asked Sep 05 '14 06:09

Rhys Stephens


1 Answers

Answer of 1st question :- Just Include JS files i.e Jquery Unobtrusive js file in your partial view which you are opening as modal then it work fine ,some times this problem comes in partial view in asp.net mvc.

Just include this js file in your Partial View also :

<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

or try this in Partial View:

$.validator.unobtrusive.parse($("form"));

Answer of 2nd and 3rd question :- As I have seen in your question you are already using Ajax.BeginForm() so it should not reload the page while submitting the form ... just check that you have included jquery.unobtrusive-ajax.min.js js file or not.

And also add below code in web.config file:

<appSettings>
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
like image 144
Kartikeya Khosla Avatar answered Sep 24 '22 01:09

Kartikeya Khosla