65.9K
CodeProject 正在变化。 阅读更多。
Home

可重用的 MVC.NET JQuery 模态弹出框

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.33/5 (8投票s)

2016年4月6日

CPOL

3分钟阅读

viewsIcon

40135

downloadIcon

1994

一个可重用的 jQuery 弹出消息框, 具有 Ajax 功能 - 可以绑定到任何模型

引言

显示一个可重用的 jQuery 模态弹出框。jQuery 模态弹出框的内容部分可以动态绑定到您选择的任何数据模型。因此,该模态框允许开发人员通过多种有用的技术“注入”HTML 内容。

背景

您需要对 jQuery、MVC 和 C# 代码有很好的理解。

简单示例:使用代码

使用此控件非常简单

  1. 确保将辅助控件添加到您的页面。
  2. 确保分配所有必要的属性。
  3. 添加您希望在模态内容部分中看到的额外 HTML
          @using (Html.BeginPopupModal(new PopupModel("messageDialog") {
            Title = "Hi there",
            TitleImageUrl = "~/Images/User_Male_Check.png", 
            PopupButtonSet = PopupButtonSet.OkPostbackClose,
            ClientFunction = "SavePerson()" }))
        {
            // all the Person Model data will be bound within into this Content section
            @Html.Partial("_Person");          
        }

设置模态弹出框控件的属性

    // Set up what values you want in your pop-up modal control.    
    Title = "Hi there",
    TitleImageUrl = "~/Images/User_Male_Check.png", 
    PopupButtonSet = PopupButtonSet.OkPostbackClose,
    ClientFunction = "SavePerson()"

当在模态弹出框控件内单击“确定”按钮时,您可以决定事件触发后执行什么操作。在我的示例中:将执行客户端函数“SavePerson()”。在此函数中,您可以决定是调用 Web API 还是 Controller 方法。

模态窗口的内容包装在一个隐藏的 DIV 内部 - 您可以自由地放置与您的模态弹出框相关的任何内容(HTML)。开发人员决定在模态弹出框内的“确定”按钮单击后会发生什么。因此,您可以决定更改模态弹出框的消息,如下所示。或者,如果需要,可以重定向到另一个页面。

客户端函数调用

    // Here is the client side function. In this example once the "ok" button is clicked
    // I take the values from the modal 'page' and do a GET to a 
    // Controller Method named: "/Home/SavePerson"

    function SavePerson() {
        var name = $("#txtName").val();
        var address = $("txtAddress").val();
        var data = JSON.stringify({ Name: name, Address: address });
  
        //lets make a Ajax call to the Controller Method
         $.ajax({
            url: "/Home/SavePerson?JSONString=" + data,
            datatype: "application/json",
            type: "GET",
            success: function (data) {
                $('.messageDialog-content').html(data);
            },
            error: function (e) {
                $(".messageDialog-content").html("ERROR");
            }
        });}

服务器端控制器方法调用

        // Here the controller method is called. 
        // The developers can decide what to do with the incoming parameters.

        public ActionResult SavePerson(string JSONString)
        {
            using (Stream jsonSource = Utilities.StringToStream(JSONString))
            {
                // serializer will read data stream
                var s = new DataContractJsonSerializer(typeof(Person));
                var person = (Person)s.ReadObject(jsonSource);
                return Content("Well done " + person.Name + ". You clicked on the OK button");
            }
        }

扩展示例

我还包含了一个更“复杂”的示例 - 或者说是一个更贴近实际的示例。在此示例中,我展示了如何将弹出框与 GridList 结合使用。您可以在这里找到此示例:“/People/Index”。

在此示例中,您可以看到我将模态弹出框控件添加到 foreach 循环正下方。

@foreach (var item in Model)
    {
        < tr>
            < td>
                @Html.DisplayFor(modelItem => item.Value.Name)
            < /td>
            < td>
                @Html.DisplayFor(modelItem => item.Value.LastName)
            < /td>
            < td>
                @Html.DisplayFor(modelItem => item.Value.Address)
            < /td>
            < td>
                < a href="#" data-id="@item.Key" class="my-edit">Edit< /a>
            < /td>
        < /tr>
    }

为了更新必要的行,必须跟踪要显示用于更新的记录“key”。通过确保将键值作为data-id”属性添加到“edit”超链接中来实现。

<a href="#" <b>data-id="@item.Key"</b> class="my-edit">Edit< /a>

现在我们确切知道我们正在尝试编辑哪一行项目 - 我们可以调用服务器来提取该特定对象的详细信息到弹出模态框中。

注意:与其只返回一个简单的 JSON 对象,我认为将实际的视图(在本例中为“_Person.cshtml”)拉入,将其转换为部分 HTML 片段会更好。这样 - 我们就不需要担心在客户端填充任何字段/输入,因为在模型绑定到视图后,大部分工作将为我们完成。

public ActionResult GetPerson(string idx)
{
    Person person;
    if (people.TryGetValue(int.Parse(idx), out person))
    {

       return PartialView("~/Views/Home/_Person.cshtml", person);

       //you could also pass a JSON object of the Person Model - if you so wished
       //you have to "AllowGet" to pass the security restriction
       //return Json(person, JsonRequestBehavior.AllowGet);
     }
     else
        return null;
}

现在我们有能力更新此 Person 对象的任何一个属性。

再次说明:您会注意到我的一个参数的类型是“Person” - 从而简化了实际更新过程。

[HttpPost]
public ActionResult Edit(int id, Person person)
{
   Person found;
   int key = int.Parse(id.ToString());
   if (people.TryGetValue(key, out found))
   {
       found.Name = person.Name;
       found.Address = person.Address;
       found.LastName = person.LastName;

       return Content("Well done. " + found.Name + " - has now been updated!");
    }
    else
    {
       return Content("Nope! Something went wrong.");
    }        
}

完成了。我们已成功更新集合中的一个项目。

请随时下载页面顶部的源代码。

尽情享用!

© . All rights reserved.