使用MVC框架中要注意的问题(五):如何在页面和用户控件之间传递数据

来源:互联网 发布:手机精美时钟软件 编辑:程序博客网 时间:2024/05/29 07:14

在MVC中,页面被称为View,而用户控件则被称为PartialView。如何在它们之间传递数据呢?

答案是:

  • 默认情况下,PartialView能够访问到View里面的 ViewData.
  • 如果页面在RenderPartial的时候,希望特别地传递数据,则按照下面的方法
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage>" %><asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">    相册asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">    <%        Html.RenderPartial("Gallery", ViewData["my"], new ViewDataDictionary() { { "Title", "我的相册" } });    %>        <%        Html.RenderPartial("Gallery", ViewData["public"], new ViewDataDictionary() { { "Title", "公开的相册" } });    %>    asp:Content><asp:Content ID="Content3" ContentPlaceHolderID="head" runat="server">asp:Content>

.csharpcode, .csharpcode pre{font-size: small;color: black;font-family: consolas, "Courier New", courier, monospace;background-color: #ffffff;/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt {background-color: #f4f4f4;width: 100%;margin: 0em;}.csharpcode .lnum { color: #606060; }

上例中,我们需要在一个页面中分别显示“我的相册”和“公开的相册”。很显然,它们除了标题和数据不同之外,基本的格式和操作都是一样的,所以我们会用一个控件来封装一下。

而在具体要Render的时候,动态地给出数据和标题即可。

原创粉丝点击