MVC 4模态窗口和AJAX

本文关键字:AJAX 窗口 模态 MVC | 更新日期: 2023-09-27 18:09:29

我正在使用MVC 4和实体框架来开发一个web应用程序。我有一个包含人员的表。还有一个Edit按钮,它调用一个模态窗口,由于它,用户可以编辑一个人。我使用的是局部视图。

我的问题是:在我的行动,我返回一个视图,但我只是想,当我点击保存按钮,模态窗口消失,我的表更新。任何想法?

动作:

[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);
}

局部视图(实际上是模态窗口):

@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>

和调用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');
           });
    });
});

MVC 4模态窗口和AJAX

需要做一些修改,但在这种情况下,我要做的是

1)将EditPerson post方法从actionresult更改为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)添加一个javascript函数来关闭模态
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)然后更新你的Ajax调用,当它成功时执行代码

@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 
                }))
{ ...

几个提示

我不喜欢MVC ajax助手。我认为它们是臃肿的,我觉得有其他框架在这方面做得更好。这是我的看法。每个人都有自己的想法。我更喜欢自己使用jQuery ajax库。我认为它更容易使用,但同样,这取决于你。

OnSuccess表示"服务器成功",而不是保存成功。所以要小心。

免责声明:我写这篇文章的时候很累,所以可能不是100%,如果有任何问题请告诉我。

好运

在POST操作中,您可以返回以下内容:

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

在Ajax的AjaxOptions中。

OnSuccess = "Modal.onAjaxSuccess"

然后在script.js中:

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

这将关闭窗口,但我仍然无法得到与引导模态相关的黑暗屏幕消失,它也不会使用AJAX更新DIV -也许Darin可以透光?


如果你还不知道怎么做,这是怎么做的:

您有一个返回人员列表的GET操作:

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

然后有一个JS函数,当你点击保存(即btn-save-new-person)的模态,允许你创建新的人触发:

$(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);
        });
    });
});

在我的动作,我返回一个视图,但我只是想,当我点击保存按钮,模态窗口消失,我的表更新。任何想法?

不是从这个控制器动作返回一个视图,而是返回一个包含表的部分视图。然后在AJAX调用的成功回调中简单地更新相应的容器。