繁体   English   中英

如何加载局部视图<DIV>标签?

[英]How to load partial view in <DIV> tag?

我还在学习MVC。 我在使用部分视图时遇到问题。 我有一个带有下拉值的页面。 每当用户选择该值时,就会出现一个带有数据表的部分页面。

目前,我正在考虑使用 JQuery 加载函数将页面加载到 div 标签中。 但是数据表没有显示。 我的代码有问题还是有更好的方法? 请帮忙。 谢谢你。

我的看法:

    @model MVCWeb.Models.DP_Table
@{
    ViewBag.Title = "Data Patching";
}

<br />

<h2>@ViewBag.Title</h2>

<br />

<table class="table-striped table-responsive">
    <tbody>
        <tr>
            <td width="40%">
                <label class="control-label">Select Table</label>
            </td>
            <td width="10%">:</td>
            <td width="*%">
                @Html.DropDownListFor(Model => Model.DPTableID, new SelectList(Model.TableCollection,
                "DPTableId", "TableName"), "Please Select", new { @id = "ddTableName", @class = "form-control" })
            </td>
        </tr>
        <tr>
            <td><br /></td>
        </tr>
        <tr>
            <td>
                <label class="control-label">Select Action</label>
            </td>
            <td>:</td>
            <td>
                @Html.DropDownList("Actions", @ViewBag.PatchingActions as List<SelectListItem>,
                "Please Select", new { @id = "ddPatchingAction", @class = "form-control", @disabled = "disabled" })
            </td>
        </tr>
    </tbody>
</table>

<br />

<div id="divPatching"></div>

@section scripts{
    <script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

    <script>
        var ddTableValue, ddPatchingActionValue;

        $('#ddTableName').change(function () {
            ddTableValue = $('#ddTableName option:selected').val();
            if (ddTableValue) {
                $("#ddPatchingAction").prop("disabled", false);
            } else {
                $("#ddPatchingAction").prop("disabled", true);
            }
        });

        $('#ddPatchingAction').change(function () {
            ddPatchingActionValue = $('#ddPatchingAction option:selected').val();
            if (ddPatchingActionValue) {
                $("#divPatching").load('@Url.Action("GetPartialView", "DataPatching")');
            }
        });
    </script>
}

我的控制器:

public PartialViewResult GetPartialView()
    {
        return PartialView("~/Views/PatchingBatch/Index.cshtml");
    }

我的部分观点:

<a class="btn btn-success" style="margin-bottom:10px" onclick="AddUserForm('@Url.Action("AddUser", "Account")')"><i class="fa fa-plus"></i> Add New User</a>
<table id="batchTable" class="table-striped table-responsive">
    <thead>
        <tr>
            <th>Username</th>
            <th>Name</th>
            <th>Email Address</th>
            <th>Is Admin</th>
            <th></th>
        </tr>
    </thead>
</table>


<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

@section scripts{
    <script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

    <script>
        var popup, dataTable;

        $(document).ready(function () {
            dataTable = $("#batchTable").DataTable({
                "ajax": {
                    "url": "/Account/GetDPUserList",
                    "type": "POST",
                    "datatype": "json"
                },

                "columns": [
                    { "data": "Username", "name":"Username" },
                    { "data": "Name", "name": "Name"  },
                    { "data": "Email", "name": "Email"  },
                    { "data": "IsAdmin", "name": "IsAdmin" },
                    {
                        "data": "DPUserID", "render": function (data) {
                            return "<a class='btn btn-primary btn-sm' onclick=EditUserForm('@Url.Action("UpdateUser", "Account")/" + data +"')><i class='fa fa-pencil'></i> Edit</a><a class='btn btn-danger btn-sm'  style='margin-left: 5px' onclick=Delete(" + data +")><i class='fa fa-trash'></i> Delete</a>";
                        },
                        "orderable": false,
                        "searchable": false,
                        "width": "150px"
                    },

                ],

                "processing": "true",
                "serverSide": "true",
                "order": [0, "asc"]
            });
        });

        function AddUserForm(url) {
            var formDiv = $('<div/>');

            $.get(url)
                .done(function (response) {
                    formDiv.html(response);

                    popup = formDiv.dialog({
                        autoOpen: true,
                        resizable: false,
                        title: "Add User Account",
                        height: 250,
                        width: 300,
                        close: function () {
                            popup.dialog('destroy').remove();
                        }
                    });
                });
        }

        function EditUserForm(url) {
            var formDiv = $('<div/>');

            $.get(url)
                .done(function (response) {
                    formDiv.html(response);

                    popup = formDiv.dialog({
                        autoOpen: true,
                        resizable: false,
                        title: "Update User Account",
                        height: 410,
                        width: 300,
                        close: function () {
                            popup.dialog('destroy').remove();
                        }
                    });
                });
        }

        function SubmitForm(form) {
            $.validator.unobtrusive.parse(form);

            if ($(form).valid()) {
                $.ajax({
                    type: "POST",
                    url: form.action,
                    data: $(form).serialize(),
                    success: function (data) {
                        if (data.success) {
                            popup.dialog('close');
                            dataTable.ajax.reload();

                            $.notify(data.message, {
                                globalPosition: "top center",
                                className: "success"
                            })
                        }
                    }
                });
            }
            return false;
        }

        function Delete(id) {
            if (confirm("Are you sure you want to delete this data?")) {
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("DeleteUser", "Account")/' + id,
                    success: function (data) {
                        if (data.success) {
                            dataTable.ajax.reload();
                            $.notify(data.message, {
                                globalPosition: "top center",
                                className: "success"
                            })
                        }
                    }
                }
                )
            }
        }
    </script>
}

我的部分控制器:

public ActionResult Index()
{
    return PartialView();
}

[HttpPost]
public ActionResult GetDPUserList()
{
    //server side parameter
    int start = Convert.ToInt32(Request["start"]);
    int length = Convert.ToInt32(Request["length"]);
    string searchValue = Request["search[value]"];
    string sortColumnName = Request["columns[" + Request["order[0][column]"] + "][name]"];
    string sortDirection = Request["order[0][dir]"];

    List<DP_User> userList = new List<DP_User>();
    using (DBModel db = new DBModel())
    {
        userList = db.DP_User.ToList<DP_User>();
        userList = userList.ToList<DP_User>();
        int totalrows = userList.Count();

        //search
        if (!string.IsNullOrEmpty(searchValue))
        {
            userList = userList.Where(x => (x.Username != null && x.Username.ToString().ToLower().Contains(searchValue)) ||
            (x.Name != null && x.Name.ToString().ToLower().Contains(searchValue)) ||
            (x.Email != null && x.Email.ToString().ToLower().Contains(searchValue))).ToList<DP_User>();
        }

        int totalrowsafterfilter = userList.Count();

        //sorting
        if (!string.IsNullOrEmpty(sortColumnName) && !string.IsNullOrEmpty(sortDirection))
        {
            userList = userList.OrderBy(sortColumnName + " " + sortDirection).ToList<DP_User>();
        }

        //paging
        userList = userList.Skip(start).Take(length).ToList<DP_User>();

        return Json(new { data = userList, draw = Request["draw"], recordsTotal = totalrows, recordsFiltered = totalrowsafterfilter },
            JsonRequestBehavior.AllowGet);
    }
}

1-为Page名称创建一个Partial View

2-创建一个Action

public ActionResult YourPage()
    {
        return PartialView("~/Views/Page.cshtml");
    }

3-To Your View 创建一个div

<div id="MyDiv"></div>

4-将此代码写入script

$(document).ready(function () {
        $.get("/Home/YourPage", function (data) {
            $('#MyDiv').html(data);
        });
    });

如果您在 ASP.NET 核心中,则可以使用此命令

<partial name="_yourPartial" />

它将从控制器中的方法为您加载视图

如果您使用的是旧版本的 ASP.NET,则可以使用此旧命令

@Html.Partial("_yourPartial")

它的工作方式相同,并避免使用 jquery

你也可以通过它传递一个模型,使用命令

@Html.Partial("_yourPartial", new { paramName = "foo" })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM