MVC 4模态窗口和AJAX

I'm using MVC 4 and Entity Framework to develop an web app. I have a table which contains persons. There is also an Edit button which invokes a modal window and thanks to it, the user can edit a person. I'm using a partial view to do so.

My question is : in my action, I return a View but I just want that when I click on the Save button, the modal window disappear and my table is updated. Any idea?

The actions :

[HttpGet]
public ActionResult EditPerson(long id)
{
    var person = db.Persons.Single(p => p.Id_Person == id);

    ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name", person.Id_ProductPackageCategory);

    return PartialView("_EditPerson", person);
}

[HttpPost]
public ActionResult EditPerson(Person person)
{

    ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name", person.Id_ProductPackageCategory);

    if (ModelState.IsValid)
    {
        ModelStateDictionary errorDictionary = Validator.isValid(person);

        if (errorDictionary.Count > 0)
        {
            ModelState.Merge(errorDictionary);
            return View(person);
        }

        db.Persons.Attach(person);
        db.ObjectStateManager.ChangeObjectState(person, EntityState.Modified);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(person);
}

The partial view (actually, the modal window) :

@model BuSIMaterial.Models.Person

<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Edit</h3>
</div>
<div>

@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
                    new AjaxOptions
                    {
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod = "POST",
                        UpdateTargetId = "table"
                    }))
{

    @Html.ValidationSummary()
    @Html.AntiForgeryToken()

    @Html.HiddenFor(model => model.Id_Person)

    <div class="modal-body">
       <div class="editor-label">
            First name :
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.FirstName, new { maxlength = 50 })
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>
        <div class="editor-label">
            Last name :
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.LastName, new { maxlength = 50 })
            @Html.ValidationMessageFor(model => model.LastName)
        </div>
        <div class="editor-label">
            National number :
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.NumNat, new { maxlength = 11 })
            @Html.ValidationMessageFor(model => model.NumNat)
        </div>
        <div class="editor-label">
            Start date :
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.StartDate, new { @class = "datepicker", @Value = Model.StartDate.ToString("yyyy/MM/dd") })
            @Html.ValidationMessageFor(model => model.StartDate)
        </div>
        <div class="editor-label">
            End date :
        </div>
        <div class="editor-field">
            @if (Model.EndDate.HasValue)
            {
                @Html.TextBoxFor(model => model.EndDate, new { @class = "datepicker", @Value = Model.EndDate.Value.ToString("yyyy/MM/dd") })
                @Html.ValidationMessageFor(model => model.EndDate)
            }
            else
            {
                @Html.TextBoxFor(model => model.EndDate, new { @class = "datepicker" })
                @Html.ValidationMessageFor(model => model.EndDate)
            }
        </div>
        <div class="editor-label">
            Distance House - Work (km) :
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.HouseToWorkKilometers)
            @Html.ValidationMessageFor(model => model.HouseToWorkKilometers)
        </div>
        <div class="editor-label">
            Category :
        </div>
        <div class="editor-field">
            @Html.DropDownList("Id_ProductPackageCategory", "Choose one ...")
            @Html.ValidationMessageFor(model => model.Id_ProductPackageCategory) <a href="../ProductPackageCategory/Create">
                Add a new category?</a>
        </div>
        <div class="editor-label">
            Upgrade? :
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Upgrade)
            @Html.ValidationMessageFor(model => model.Upgrade)
        </div>
    </div>
    <div class="modal-footer">
        <button class="btn btn-inverse" type="submit">Save</button>
    </div>
}

</div>

And my script which invokes the modal :

$(document).ready(function () {

    $('.edit-person').click(function () {
           var id = $(this).data("id");
           var url = '/Person/EditPerson/'+id;
           $.get(url, function(data) {

               $('#edit-person-container').html(data);
               $('#edit-person').modal('show');

           });
    });

});

in my action, I return a View but I just want that when I click on the Save button, the modal window disappear and my table is updated. Any idea?

Instead of returning a view from this controller action you could return a partial view containing the table. And then in the success callback of the AJAX call simply update the corresponding container.

In your POST action you could return the following:

return Json(new { error = false, message = "Person edited." });

In the AjaxOptions in Ajax.BeginForm add this:

OnSuccess = "Modal.onAjaxSuccess"

Then somewhere, say in script.js:

function onAjaxSuccess(data, status, xhr) {
    if (data.error) {
        $.notify({
            type: "error",
            text: data.message
        });
    }
    else {
        $('.modal').modal('hide');
    }
}

This will close the window, but I'm still unable to get the darkened screen associated with Bootstrap modals to go away, it also won't update the DIV using AJAX - maybe Darin can shed some light?


If you're still wondering how to do this, this is how:

You have a GET action that returns the list of people:

[HttpGet]
public ActionResult People()
{
    return PartialView("_ListOfPeoplePartial");
}

Then have a JS function that fires when you click save (i.e. btn-save-new-person) on the modal that allows you to create new people:

$(function () {
    $(document.body).on('click', '#btn-save-new-person', function (e) {
        $('#create-new-person-modal').modal('hide');
        $('body').removeClass('modal-open');
        $('.modal-backdrop').remove();
        var url = "/Home/People";
        $.get(url, function (data){
            $('#list-of-people').html(data);
        });
    });
});

a couple of changes would need to be made but here is what I would do this case

1) change the EditPerson post method from an actionresult to a JsonResult

[HttpPost]
public JsonResult EditPerson(Person person) 
{

    // code here to save person

    bool success = true; // somehow determine if the save was successful
    string msg = ""; // error message is needed?
    return JsonResult(new {success,msg, person});
}

2) Add a javascript function to close the modal

function closeModal(response){

    // the response is the Json Result sent back from the action

    if (response.success === true){
        // actually got a true response back
    }
    $('#edit-person').modal('show'); // or similar code
}

3) Then Update your Ajax call to perform code on when its successful

@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
                new AjaxOptions
                {
                    InsertionMode = InsertionMode.Replace,
                    HttpMethod = "POST",
                    UpdateTargetId = "table",
                    OnSuccess = "closeModal(response);" // or javascript code to close the modal, you can also 
                }))
{ ...

a couple of tips

I don't like the MVC ajax helpers. I think they are bloated and I feel there are other frameworks better at it. Thats my opinion. To each their own though. I would prefer to use the jQuery ajax library myself. I think its easier to use but again, its up to you.

The OnSuccess means on "Server Success" not save success. so be careful.

Disclaimer: I wrote this while tired and so it might not be 100% let me know of any issues.

Good luck