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

MVC.NET 模态窗口小部件助手

starIconstarIconstarIconstarIconstarIcon

5.00/5 (7投票s)

2016年9月14日

CPOL

2分钟阅读

viewsIcon

29738

downloadIcon

498

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

引言

我希望概述一种用于创建可重用 MVC 控制的小部件工厂模式。在这个例子中,我决定创建一个可重用的“MVC”模态弹出窗口小部件。借助 MVC HtmlHelper,我可以轻松地在 Razor “HTML” 类上创建一个扩展,以实现我自己的自定义弹出控件。

背景

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

Using the Code

将控件添加到您的视图非常容易。

  1. 确保将小部件控件添加到您的页面上。
  2. 分配所有必要的属性。定义这些属性将帮助您管理模态弹出窗口的行为。
     @(Html.HollowPoint().Window()
    .Name("modalPopup")
    .TemplateViewPath("~/Views/Shared/BootstrapModal.cshtml") 
    .Title("Hellow new world..!")
    .Resizable(false)
    .Draggable()
    .IconUrl("~/Images/User_Male_Check.png")
    )

了解您的模态弹出窗口控件的属性

    Need to define the title

    `.Title("Hellow new world..!")

    Provide a template you would like to re-use. The template is like the building blocks 
    of your client side control.
    The template needs to implement the client side UI structure of the control you wish to see. 
    In this example I provide a "Bootstrap" modal HTML template.

    .TemplateViewPath("~/Views/Shared/BootstrapModal.cshtml")

控件实际应用

我包含了一个例子,其中我列出了一堆在 gridview 中显示的“People”。在这个例子中,我展示了如何将弹出窗口与 GridList 结合使用。这允许我从同一页面快速编辑这些人的“详细信息”。

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

	List all the people included within the provided Model

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

现在,我们需要编辑这些人中的一个。当网格中的“编辑”按钮被点击时,模态弹出控件将出现。现在我们需要“获取”我们尝试“编辑”的人的特定详细信息。在我的例子中:控制器“/People/GetPerson”将通过 Ajax 调用被调用。在这里,您可以决定是调用 Web API 还是控制器方法。

      $(".my-edit").click(function () {
        //show the 'OK' button again
        $('.modal-footer').find('.btn-primary').first().show();
        clearContent();
        //the unique key found on this particular item
        var idx = $(this).attr("data-id");
        //store this unique 'key' away - as we will be needing it later
        $("#currentID").val(idx);
        //lets go and fetch this 'person'
        $.ajax({
            url: "/People/GetPerson?idx=" + idx,
            datatype: "application/json",
            type: "GET",
            cache: false,
            success: function (data) {
                //this call created a partial view for us = and returned the HTML
                //all we need to do is place it within the modal's internal content area            
                var dialog = $("#modalPopup")
                    .modalpopup("populateContent", data)
                    .modalpopup("show");       
            },
            error: function (e) {
                var test = e;
            }
        });
    });
}

模态窗口的内部 CONTENT 包装在 DIV 内部 - 模态的内容基于返回的 Ajax 调用填充,即从服务器检索内容“HTML”。在我的例子中,我检索“Person”的内容,即:将“Person”模型绑定到部分视图:“_Person.cshtml”。

        // Here the controller method is called. You can decide what to do with the incoming parameters.
        public ActionResult GetPerson(string idx)
        {
            Person person;
            if (p.GetPeopleDictionary().TryGetValue(int.Parse(idx), out person))
            {
                //let us return a partial view - passing through the "Person" model
                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 的详细信息,必须跟踪您希望显示用于更新的记录(或“key”)。通过确保将键值作为“attribute”添加到“edit”链接中来实现这一点。

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

现在,我们有能力更新此特定 Person 的任何属性。

    [HttpPost]
        public ActionResult Edit(int id, Person person)
        {
            Person found;
            int key = int.Parse(id.ToString());
            if (p.GetPeopleDictionary().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.