【问题标题】:asp.net mvc usercontrol viewdataasp.net mvc 用户控件视图数据
【发布时间】:2010-04-18 12:16:42
【问题描述】:

我有用户控制,我在几个视图上呈现。我想在 usercontrol 中显示 viewdata,但是 viewdata 必须填写在控制器方法中,所以我需要在每个视图的每个控制器方法上填充 viewdata,我在其中渲染 usercontrol。 有没有简单的解决办法?

【问题讨论】:

    标签: asp.net-mvc user-controls viewdata


    【解决方案1】:

    为该控件设置一个控制器,例如

    菜单控制器

    带有动作方法

    RenderMenu()
    {
        **do your work to get the data here and preferrably strong type it**
        return PartialView("NameOfYourAscxFile", yourObject);
    }
    

    如果您将控件命名为 RenderMenu.ascx,则可以这样做

    RenderMenu()
    {
        **do your work to get the data here and preferrably strong type it**
        return PartialView(yourObject);
    }
    

    或者,也许将其命名为 Menu.ascx 并使用这样的方法 Menu 会更有意义

    Menu()
    {
        **do your work to get the data here and preferrably strong type it**
        Menu myMenuObject = Repository.GetMenu(...);
        return PartialView(myMenuObject);
    }
    

    您的 Menu.ascx 开始看起来像这样

    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<mynamespace.Menu>" %>
    

    要在视图中使用它,您可以这样做:

    <% Html.RenderAction("Menu", "Menu"); %>
    

    HTH

    【讨论】:

      猜你喜欢
      • 2010-09-29
      • 1970-01-01
      • 2010-11-28
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      • 2010-09-06
      相关资源
      最近更新 更多