将数据传递给母版页的ASP.NET MVC母版、ASP、MVC、NET

2023-09-02 01:22:54 作者:一直為你瘋

什么是你没有打破MVC规则将数据传递给母版页(使用ASP.NET MVC)的方法是什么?

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

我个人preFER至code抽象控制器(基控制器)或基类,它传递给所有的意见。

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

推荐答案

如果您preFER你的观点有强类型的视图数据类,这可能为你工作。其他的解决方案可能更多的正确的,但这是设计和实用性恕我直言之间一个很好的平衡。

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); %>

这是唯一的例子code和不打算编译为是。专为ASP.Net MVC 1.0。的