MVC中局部刷新PartialView(与Ajax.BeginForm结合)的用法

在MVC程序中我们通常都会用到局部刷新的功能,比如点击”搜索“按钮时 我们只希望结果Table刷新,而搜索的条件部分不变

Index页面如下:

@model IEnumerable<GetServerRelation.Models.ServerShowInfoModel>

@{
    ViewBag.Title = "IndexPage";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>IndexPage</h2>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>GetRelationTree</title>
    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
    <script type="text/javascript">
        function btnclicksea() {
            var id = $("#bssel").val();
            $('#divservices').load('/Home/GetResults?id=' + id);
        }
        function btnclickcreate() {
            var id = $("#bssel").val();
            if (confirm('Are you sure Create id?')) {
                $.ajax({
                    type: "post",
                    url: "home/CreateBusinessToCMDB",
                    data: { bsid: id },
                    dataType: "text",
                    success: function (data) {
                        if (data == "Sucess") {
                            alert("Create Sucess !");
                        }
                    }
                });
            }
            else {
                return;
            }
        }
    </script>
</head>
<body>
    <div>
        @using (Ajax.BeginForm("GetResults", "Home", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "divservices", InsertionMode = InsertionMode.Replace }))
        {
            <table>
                <tr>
                    <td><span style=" font-size:15px">Business Name :</span></td>
                    <td>
                        <select style="230px;height:26px" , Model)
    </div>
</body>
</html>

在以上Index页面中我们希望刷新的部分是>GetResults”这个Action 如下:

        [HttpPost]
        public ActionResult GetResults()
        {
            int id = Convert.ToInt32(Request.Form["bssel"]);
            List<ServerShowInfoModel> list = GetServicesByBSid(id);
            ViewBag.count = list.Count;
            return PartialView("~/Views/Home/ServiceView.cshtml", list);  //list可以是(from p in students select p).tolist();等
        }

当然我们还需要建PartialView的页面(ServiceView.cshtml) 例如:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>ServiceView</title>
</head>
<body>
    <div >@item.displayName</td>
                   
                </tr>
            }
        </table>
    </div>

</body>
</html>

注:上面标红的几个js文件必须要引用 否则可能没效果(F:/Projects/VNTDemoTest)

MVC中局部刷新PartialView(与Ajax.BeginForm结合)的用法