我是靠谱客的博主 帅气睫毛膏,这篇文章主要介绍MVC中使用PartialView返回部分HTML段,现在分享给大家,希望可以做个参考。

在asp.net mvc中返回View时使用的是ViewResult,它继承自ViewResultBase 同时它还有个兄弟PartialViewResult

相信聪明的你已经知道了它俩的区别了,没错 一个用于返回整体,另一个返回局部(部分)。

假设我有这样一个需求,输入用户名,然后返回相关信息。之前的做法可能会是用json格式来返回用户的相关信息,然后到页面去渲染相关的HTML,如果产生的相关HTML比较大的话,我还是建议你沿用之前的方案(返回json),因为传输的数据少,响应快一些。

反之,PartialViewResult 则是返回部分HTML 的不错选择。

下面就让我们看下如何使用PartialViewResult:

Layout.cshtml

复制代码
1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html> <html> <head> <title>@ViewBag.Title</title> <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script> </head> <body> @RenderBody() </body> </html>

Index.cshtml

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2> PartialView Demo</h2> <div> Please write your name here <input type='text' id='txtName' /> <input type='button' value='submit' id='btnOK' /> </div> <br /> <div id='content'> </div> <script type="text/javascript"> $(function () { $('#btnOK').click(function () { var data = { Name: $('#txtName').val()}; $.ajax({ type: "POST", url: '@Url.Action("PartialViewDemo", "Home")', data: data, datatype: "html", success: function (data) { $('#content').html(data); }, error: function () { alert("处理失败!"); } }); }); }); </script>

ViewUserControl.cshtml (Partial View)

复制代码
1
2
3
4
5
6
7
8
@model Sample.Models.PartialViewDemoViewModel <div> <h2>ViewUserControl.cshtml</h2> @Model.dt <br /><br /> Hello~ @Model.Name </div>

或者 ViewUC.ascx (View User Control)

复制代码
1
2
3
4
5
6
7
8
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Vancl.Sample.Models.PartialViewDemoViewModel>" %> <div> <h2>ViewUC.ascx</h2> <%=Model.dt %> <br /><br /> Hello~ <%=Model.Name %> </div>

Model

复制代码
1
2
3
4
5
public class PartialViewDemoViewModel { public string Name { set; get; } public DateTime? dt { set; get; } }

Action

复制代码
1
2
3
4
5
6
7
8
[HttpPost] public ActionResult PartialViewDemo(PartialViewDemoViewModel model) { model.dt = DateTime.Now; return PartialView("ViewUserControl", model); //return PartialView("ViewUC", model); }

调用 Controller.PartialView方法时,可以指定 Partial View or View User Control 效果是一样的

不写后缀时,会查找同目录和Shared目录下的文件,也就是在同目录或Shared目录下时可以省略后缀名。

如果目录下存在同名的情况,会找第一个并返回。

eg: 同目录下有 ViewUserControl.ascxViewUserControl.cshtml

这时使用 return PartialView("ViewUserControl");

会返回 ViewUserControl.ascx 的内容,因为字母a在c前 :)

如果在这种情况下想调用 ViewUserControl.cshtml

则需要写全路径,return PartialView("~/Views/Home/ViewUserControl.cshtml");

当想访问的 Partial View or View User Control 在不同目录时,也可以通过全路径的方式访问。

最后

以上就是帅气睫毛膏最近收集整理的关于MVC中使用PartialView返回部分HTML段的全部内容,更多相关MVC中使用PartialView返回部分HTML段内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(76)

评论列表共有 0 条评论

立即
投稿
返回
顶部