Skip to main content
 首页 » 编程设计

c#之MVC 4 模态窗口和 AJAX

2024年01月28日32insus

我正在使用 MVC 4 和 Entity Framework 开发网络应用程序。我有一张包含人员的表格。还有一个调用模态窗口的编辑按钮,用户可以通过它编辑一个人。我正在使用局部 View 来这样做。

我的问题是:在我的操作中,我返回了一个 View ,但我只希望当我单击“保存”按钮时,模态窗口消失并且我的表格被更新。有什么想法吗?

Action :

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

局部 View (其实就是模态窗口):

@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'); 
 
           }); 
    }); 
 
}); 

请您参考如下方法:

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

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 表示“Server Success”没有保存成功。所以要小心。

免责声明:我写这篇文章时很累,所以可能不会 100% 让我知道任何问题。

祝你好运