1

我正在使用 MVC 4 和 Entity Framework 来开发 Web 应用程序。我有一张包含人的桌子。还有一个编辑按钮,它调用一个模式窗口,并且由于它,用户可以编辑一个人。我正在使用局部视图来这样做。

我的问题是:在我的操作中,我返回了一个视图,但我只希望当我点击保存按钮时,模式窗口消失并且我的表格被更新。任何想法?

行动 :

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

还有我调用模态的脚本:

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

           });
    });

});
4

3 回答 3

2

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

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% 让我知道任何问题。

祝你好运

于 2013-04-15T12:29:08.723 回答
2

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

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

在 Ajax.BeginForm 的 AjaxOptions 中添加:

OnSuccess = "Modal.onAjaxSuccess"

然后在某个地方,在 script.js 中说:

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

这将关闭窗口,但我仍然无法让与 Bootstrap 模态相关的变暗屏幕消失,它也不会使用 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);
        });
    });
});
于 2013-04-15T12:27:00.103 回答
2

在我的操作中,我返回了一个视图,但我只希望当我点击保存按钮时,模式窗口消失并且我的表格被更新。任何想法?

您可以返回包含表格的局部视图,而不是从此控制器操作返回视图。然后在 AJAX 调用的成功回调中简单地更新相应的容器。

于 2013-04-15T12:15:50.330 回答