C# 在 ASP.NET MVC 中将数据传递到母版页

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/78548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 11:16:30  来源:igfitidea点击:

Passing data to Master Page in ASP.NET MVC

提问by ?ukasz Sowa

What is your way of passing data to Master Page (using ASP.NET MVC) without breaking MVC rules?

在不违反 MVC 规则的情况下,您将数据传递到母版页(使用 ASP.NET MVC)的方式是什么?

Personally, I prefer to code abstract controller (base controller) or base class which is passed to all views.

就个人而言,我更喜欢编写传递给所有视图的抽象控制器(基控制器)或基类。

采纳答案by Generic Error

If you prefer your views to have strongly typed view data classes this might work for you. Other solutions are probably more correctbut this is a nice balance between design and practicality IMHO.

如果您希望您的视图具有强类型的视图数据类,这可能对您有用。其他解决方案可能更正确,但恕我直言,这是设计和实用性之间的一个很好的平衡。

The master page takes a strongly typed view data class containing only information relevant to it:

母版页采用仅包含与其相关的信息的强类型视图数据类:

public class MasterViewData
{
    public ICollection<string> Navigation { get; set; }
}

Each view using that master page takes a strongly typed view data class containing its information and deriving from the master pages view data:

使用该母版页的每个视图都采用强类型视图数据类,其中包含其信息并从母版页视图数据中派生:

public class IndexViewData : MasterViewData
{
    public string Name { get; set; }
    public float Price { get; set; }
}

Since I don't want individual controllers to know anything about putting together the master pages data I encapsulate that logic into a factory which is passed to each controller:

由于我不希望单个控制器知道有关将母版页数据放在一起的任何信息,因此我将该逻辑封装到传递给每个控制器的工厂中:

public interface IViewDataFactory
{
    T Create<T>()
        where T : MasterViewData, new()
}

public class ProductController : Controller
{
    public ProductController(IViewDataFactory viewDataFactory)
    ...

    public ActionResult Index()
    {
        var viewData = viewDataFactory.Create<ProductViewData>();

        viewData.Name = "My product";
        viewData.Price = 9.95;

        return View("Index", viewData);
    }
}

Inheritance matches the master to view relationship well but when it comes to rendering partials / user controls I will compose their view data into the pages view data, e.g.

继承很好地匹配了主视图关系,但是当涉及到呈现部分/用户控件时,我会将它们的视图数据组合到页面视图数据中,例如

public class IndexViewData : MasterViewData
{
    public string Name { get; set; }
    public float Price { get; set; }
    public SubViewData SubViewData { get; set; }
}

<% Html.RenderPartial("Sub", Model.SubViewData); %>

This is example code only and is not intended to compile as is. Designed for ASP.Net MVC 1.0.

这只是示例代码,并不打算按原样编译。专为 ASP.Net MVC 1.0 设计。

回答by Ian P

Abstract controllers are a good idea, and I haven't found a better way. I'm interested to see what other people have done, as well.

抽象控制器是个好主意,我还没有找到更好的方法。我也有兴趣看看其他人做了什么。

回答by Ian P

The Request.Params object is mutable. It's pretty easy to add scalar values to it as part of the request processing cycle. From the view's perspective, that information could have been provided in the QueryString or FORM POST. hth

Request.Params 对象是可变的。作为请求处理周期的一部分,向其添加标量值非常容易。从视图的角度来看,该信息可以在 QueryString 或 FORM POST 中提供。第

回答by David Negron

I did some research and came across these two sites. Maybe they could help.

我做了一些研究,发现了这两个网站。也许他们可以提供帮助。

ASP.NET MVC Tip #31 – Passing Data to Master Pages and User Controls

ASP.NET MVC 技巧 #31 – 将数据传递到母版页和用户控件

Passing Data to Master Pages with ASP.NET MVC

使用 ASP.NET MVC 将数据传递到母版页

回答by dimarzionist

I thing that another good way could be to create Interface for view with some Property like ParentView of some interface, so you can use it both for controls which need a reference to the page(parent control) and for master views which should be accessed from views.

我认为另一种好方法可能是使用某些属性(如某些界面的 ParentView)创建用于视图的界面,因此您可以将它用于需要引用页面(父控件)的控件和应该从以下位置访问的主视图意见。

回答by Matt Mitchell

I find that a common parent for all model objects you pass to the view is exceptionally useful.

我发现传递给视图的所有模型对象的公共父级非常有用。

There will always tend to be some common model properties between pages anyway.

无论如何,页面之间总会有一些共同的模型属性。

回答by Michael La Voie

EDIT

编辑

Generic Errorhas provided a better answer below. Please read it!

通用错误在下面提供了更好的答案。请阅读!

Original Answer

原答案

Microsoft has actually posted an entry on the "official" wayto handle this. This provides a step-by-step walk-through with an explanation of their reasoning.

微软实际上已经发布了一个关于处理这个“官方”方式的条目。这提供了一步一步的演练,并解释了他们的推理。

In short, they recommend using an abstract controller class, but see for yourself.

简而言之,他们建议使用抽象控制器类,但请自行查看。

回答by rasx

The other solutions lack elegance and take too long. I apologize for doing this very sad and impoverished thing almost an entire year later:

其他解决方案缺乏优雅且耗时太长。我为几乎整整一年后做了这件非常悲伤和贫困的事情而道歉:

<script runat="server" type="text/C#">
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        MasterModel = SiteMasterViewData.Get(this.Context);
    }

    protected SiteMasterViewData MasterModel;
</script>

So clearly I have this static method Get() on SiteMasterViewData that returns SiteMasterViewData.

很明显,我在 SiteMasterViewData 上有这个静态方法 Get(),它返回 SiteMasterViewData。

回答by Todd Menier

I prefer breaking off the data-driven pieces of the master view into partials and rendering them using Html.RenderAction. This has several distinct advantages over the popular view model inheritance approach:

我更喜欢将主视图的数据驱动部分分解为部分并使用Html.RenderAction呈现它们。与流行的视图模型继承方法相比,这有几个明显的优势:

  1. Master view data is completely decoupled from "regular" view models. This is composition over inheritance and results in a more loosely coupled system that's easier to change.
  2. Master view models are built up by a completely separate controller action. "Regular" actions don't need to worry about this, and there's no need for a view data factory, which seems overly complicated for my tastes.
  3. If you happen to use a tool like AutoMapperto map your domain to your view models, you'll find it easier to configure because your view models will more closely resemble your domain models when they don't inherit master view data.
  4. With separate action methods for master data, you can easily apply output caching to certain regions of the page. Typically master views contain data that changes less frequently than the main page content.
  1. 主视图数据与“常规”视图模型完全分离。这是组合而不是继承,并导致更松散耦合的系统更容易更改。
  2. 主视图模型由完全独立的控制器操作构建。“常规”操作不需要担心这个,也不需要视图数据工厂,这对我的口味来说似乎过于复杂。
  3. 如果您碰巧使用AutoMapper 之类的工具将域映射到视图模型,您会发现配置起来更容易,因为当视图模型不继承主视图数据时,它们将更类似于域模型。
  4. 使用针对主数据的单独操作方法,您可以轻松地将输出缓存应用于页面的某些区域。通常,母版视图包含的数据更改频率低于主页内容。