在 ASP.NET MVC 中将数据传递到母版页 [英] Passing data to Master Page in ASP.NET MVC

查看:39
本文介绍了在 ASP.NET MVC 中将数据传递到母版页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

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

If you prefer your views to have strongly typed view data classes this might work for you. Other solutions are probably more correct but 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); %>

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

这篇关于在 ASP.NET MVC 中将数据传递到母版页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆