mvc ajax submitting from a modal

2019-09-06 00:10发布

问题:

I call a modal which allows a user to select a bunch of dynamically created check boxes and then submit the form to a controller which saves all the info from the FormCollection passed in to it then does a RedirectToAction to the page that calls the modal.

I want to be able to still to save the stuff in the form, but, instead of redirecting to the page that calls the modal i want to stay in the modal.

modal

<script type="text/javascript">
// Close Modal when done.
function CloseModal() {
    $("#SkillModalWindow").modal("hide");
}
</script>

@using (Ajax.BeginForm("Save", "SkillGroup", null, new AjaxOptions
{
    HttpMethod = "Post",
    OnSuccess = "CloseModal"
},
new { id = "CreateSkillGroups" }))
{
@Html.ValidationSummary(true)
@Html.Hidden("JobRoleId", (int)ViewBag.JobRoleID)

<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Add New Skills to Job Role</h3>
</div>
<div class="modal-body" id="CreateModal">@Html.Partial("_Create")</div>
<div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button type="submit" class="btn btn-primary">Save</button>
</div>
}

Controllor Action

[HttpPost]
public ActionResult Save(FormCollection formCollection)
{

foreach (var key in formCollection.AllKeys)
{
    do stuff.....

}
return RedirectToAction("Index");

}

回答1:

You could return a partial view containing the modal markup instead of redirecting:

[HttpPost]
public ActionResult Save(FormCollection formCollection)
{

    foreach (var key in formCollection.AllKeys)
    {
        do stuff.....

    }
    return PartialView("_Modal");
}

Also make sure that you have included the jquery.unobtrusive-ajax.js script in your main view if you want the Ajax.BeginForm helper to work.