如何在" Site.Master"中使用ViewUserControl页

时间:2015-04-18 00:15:06

标签: asp.net asp.net-mvc

我有" TopHeader.ascx" (ViewUserControl)如下:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TopHeader.ascx.cs" Inherits="Sample.Web.CMS.Navigation.TopHeader" %>
<div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <span class="flow-text selected-menu-option">
                <%
                    var s = Model.FirstOrDefault(i => i.IsSelected);
                    s = s ?? Model[0];
                %>
                <%= s.Caption %>
                <i class="glyphicon glyphicon-menu-right"></i>
            </span>
        </div>
    </div>
</div>

public partial class TopHeader : ViewUserControl<List<MenuItem>>
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

public class MenuItem
{
    public string Caption { get; set; }
    public string Url { get; set; }
    public bool IsSelected { get; set; }
}

在_Layout.cshtml中,我有以下内容,它完全正常:

<body>
    @Html.Partial("~/Navigation/TopHeader.ascx", new List<MenuItem>() { new MenuItem() { Caption = "Constituents", IsSelected = true}, new MenuItem() { Caption = "Fund Raising" }, new MenuItem() { Caption = "Orders" }, new MenuItem() { Caption = "Products" }, new MenuItem() { Caption = "Reporting" } })

</body>

现在,我想使用相同的&#34; TopHeader.ascx&#34;在&#34; Site.Master&#34;其定义如下:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="Sample.Web.CMS.SiteMaster" %>

代码隐藏

public partial class SiteMaster : MasterPage
{
...
}

我如何使用&#34; TopHeader.ascx&#34;在&#34; Site.master&#34;。如何使用某些(菜单)数据实例化控件(就像我在顶部的MVC View中所做的那样)?

1 个答案:

答案 0 :(得分:0)

Site.master中添加与_Layout.cshtml中基本相同的代码,除了两项更改:

  1. 在WebForms视图引擎中,您使用<%: whatever %>代替@whatever
  2. 使母版页成为MVC ViewMasterPage
  3. 因此,将母版页更改为:

    public partial class SiteMaster : MasterPage
    {
        ...
    }
    

    并使用此代码呈现部分:

    <%: Html.Partial("~/Navigation/TopHeader.ascx",
        new List<MenuItem>() {
            new MenuItem() { Caption = "Constituents", IsSelected = true },
            new MenuItem() { Caption = "Fund Raising" },
            new MenuItem() { Caption = "Orders" },
            new MenuItem() { Caption = "Products" },
            new MenuItem() { Caption = "Reporting" } })
    %>