简体   繁体   English

asp.net mvc用户控件视图数据

[英]asp.net mvc usercontrol viewdata

i have user control, which i render on several views. 我有用户控件,可以在多个视图上进行渲染。 i want to show viewdata in the usercontrol, but viewdata must be filled in controller method, so i need to fill viewdata on each controller method of each view, where i render usercontrol. 我想在用户控件中显示viewdata,但必须在controller方法中填充viewdata,因此我需要在渲染usercontrol的每个视图的每个控制器方法中填充viewdata。 is there any simple solutions? 有没有简单的解决方案?

Have a controller for that control like 有一个控制器来控制

MenuController MenuController

with an action method 用行动方法

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

If you name your control RenderMenu.ascx, you can just do 如果您将控件命名为RenderMenu.ascx,则只需执行

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

Or, maybe it would make more sense to name it Menu.ascx and have a method Menu like this 或者,将其命名为Menu.ascx并具有如下所示的Menu方法可能更有意义

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

Your Menu.ascx start would look like this 您的Menu.ascx开始看起来像这样

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

To use it in a View you do it like this: 要在视图中使用它,您需要这样做:

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

HTH HTH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM