[ASP.NET MVC 小牛之路]12 - Section、Partial View 和 Child Action

概括的讲,View中的内容可以分为静态和动态两部分。静态内容一般是html元素,而动态内容指的是在应用程序运行的时候动态创建的内容。给View添加动态内容的方式可归纳为下面几种:

  • Inline code,小的代码片段,如 if 和 foreach 语句。
  • Html helper方法,用来生成单个或多个HTML元素,如view model、ViewBag等。
  • Section,在指定的位置插入创建好的一部分内容。
  • Partial view,存在于一个单独的视图文件中,作为子内容可在多个视图中共享。
  • Child action,相当于一个包含了业务逻辑的UI组件。当使用child action时,它调用 controller 中的 action 来返回一个view,并将结果插入到输出流中。

这个分类不是绝对的。前两种很简单,在前面的文章中也使用过。本文主要介绍后三种方式的应用。

本文目录

Section

Razor视图引擎支持将View中的一部分内容分离出来,以便在需要的地方重复利用,减少了代码的冗余。下面来演示如何使用Section。

创建一个MVC应用程序,选择基本模板。添加一个HomeController,编辑生成的Index方法如下:

public ActionResult Index() {
    string[] names = { "Apple", "Orange", "Pear" };
    return View(names);
} 

右击Index方法,添加视图,编辑该视图如下:

@model string[] 
 
@{ 
    ViewBag.Title = "Index"; 
} 
 
@section Header { 
    <div class="view"> 
        @foreach (string str in new [] {"Home", "List", "Edit"}) { 
            @Html.ActionLink(str, str, null, new { style = "margin: 5px" })   
        } 
    </div> 
}

<div class="view"> 
    This is a list of fruit names: 
    @foreach (string name in Model) { 
        <span><b>@name</b></span> 
    } 
</div>

@section Footer { 
    <div class="view"> 
        This is the footer 
    </div> 
} 

我们通过@section标签加section的名称来定义一个Section,这里创建了两个section:Header 和 Footer,习惯上一般把section放在View文件的开头或结尾以方便阅读。下面我们在 /Views/Shared/_Layout.cshtml 文件中来使用它们。

编辑 /Views/Shared/_Layout.cshtml 文件如下:

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8" /> 
    <meta name="viewport" content="width=device-width" /> 
    <style type="text/css"> 
        div.layout { background-color: lightgray;} 
        div.view { border: thin solid black; margin: 10px 0;} 
    </style> 
    <title>@ViewBag.Title</title> 
</head> 
<body>
    @RenderSection("Header") 
 
    <div class="layout"> 
        This is part of the layout 
    </div> 
 
    @RenderBody() 
 
    <div class="layout"> 
        This is part of the layout 
    </div>

    @RenderSection("Footer")
<div class="layout"> 
        This is part of the layout 
    </div> 
</body> 
</html> 

我们通过 @RenderSection 方法来调用section的内容,参数指定了section的名称。运行程序后可以看到如下结果:

注意,section只能在当前View或它的Layout中被调用。@RenderSection方法没有找到参数指定的section会抛异常,如果不确定section是否存在,则需要指定第二个参数的值为false,如下:

... 
@RenderSection("scripts", false) 
... 

我们还可以通过 IsSectionDefined 方法来判断一个section是否被定义或在当前View中是否能调用得到,如:

... 
@if (IsSectionDefined("Footer")) { 
    @RenderSection("Footer") 
} else { 
    <h4>This is the default footer</h4>    
} 
...

Partial View

Partial view(分部视图)是将部分 Razor 和 Html 标签放在一个独立的视图文件中,以便在不同的地方重复利用。接下来介绍如何使用 partial view。

我们先来创建一个partial view 。在 /Views/Shared 目录下新建一个名为 MyPartial 的视图文件,勾选“创建为分部视图”,如下:

添加好的 partial view 文件是一个空文件,我们在这个文件中添加如下代码:

<div>
    This is the message from the partial view.
    @Html.ActionLink("This is a link to the Index action", "Index")
</div> 

这个 MyPartial.cshtml 视图用将创建一个回到首页的连接。当然这里的 @Html.ActionLink 方法也是一种(Html helper)动态加载View内容的方式。

然后在 HomeController 中添加一个List action方法,如下:

public ActionResult List()
{
    return View();
}

继续为此添加一个 List.cshtml 视图,并通过@Html.Partial方法来调用我们要呈现的分部视图,如下:

@{
    ViewBag.Title = "List";
    Layout = null;
}
<h3>This is the /Views/Home/List.cshtml View</h3>
@Html.Partial("MyPartial")

视图引擎将按照规定的顺序先后在 /Views/Home 和 /Views/Shared 文件夹下查找 MyPartial 视图。

运行程序导航到 /Home/List,我们可以看到如下效果:

Partial view 和普通和 View 的使用没有什么区别,也可以使用强类型,如我们在 MyPartial.cshtml 中通过 @model 指定 model 的类型:

@model IEnumerable<string>

<div>
    This is the message from the partial view.
    @Html.ActionLink("This is a link to the Index action", "Index")
    
    <ul>
        @foreach (string str in Model)
        {
            <li>@str</li>
        }
    </ul>
</div> 

并修改调用 MyPartial.cshtml 视图的主视图 List.cshtml 如下:

@{
    ViewBag.Title = "List";
    Layout = null;
}
<h3>This is the /Views/Home/List.cshtml View</h3>
@Html.Partial("MyPartial", new[] { "Apple", "Orange", "Pear" })

和上面不同的是,这里我们给 @Html.Partial 指定了第二个参数,将一个数组传递给了 MyPartial.cshtml 的 model 对象。运行效果如下:

Child Action

Child action 和 Patial view 类似,也是在应用程序的不同地方可以重复利用相同的子内容。不同的是,它是通过调用 controller 中的 action 方法来呈现子内容的,并且一般包含了业务的处理。任何 action 都可以作为子 action 。接下来介绍如何使用它。

在 HomeController 中添加一个 action,如下:

[ChildActionOnly]
public ActionResult Time()
{
    return PartialView(DateTime.Now);
}

这个 action 通过调用 PartialView 方法来返回一个 partial view。ChildActionOnly 特性保证了该 action 只能作为子action被调用(不是必须的)。

接着我们继续为这个action添加一个相应的 Time.cshtml 视图,代码如下:

@model DateTime

<p>The time is: @Model.ToShortTimeString()</p> 

在 List.cshtml 视图中添加如下代码来调用 Time action 方法 :

...
@Html.Action("Time")

运行结果如下:

我们通过 @Html.Action 方法来调用了 Time action 方法来呈现子内容。在这个方法中我们只传了一个action名称参数,MVC将根据当前View所在Controller去查找这个action。如果是调用其它 controller 中的 action 方法,则需要在第二个参数中指定 controller 的名称,如下:

... 
@Html.Action("Time", "MyController") 

该方法也可以给 action 方法的参数传值,如对于下面带有参数的 action:

... 
[ChildActionOnly] 
public ActionResult Time(DateTime time) { 
    return PartialView(time); 
}

我们可以这样使用 @Html.Action 方法:

... 
@Html.Action("Time", new { time = DateTime.Now })

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值