0

我有一个独特的场景,我希望基本控制器获取一些数据并将其存储在列表中。该列表应该可以从我的视图中访问,就像 ViewData 一样。我将在每一页上使用这个列表,并且想要一个更简洁的解决方案,而不是仅仅将它推到 ViewDataDictionary 中。

在尝试提出解决方案后,我想我会创建一个自定义 ViewPage 并带有一个属性来保存我的列表。我的自定义 ViewPage 将继承自 System.Web.MVC.ViewPage。但是,我不知道 MVC 将视图数据从控制器传递到视图的位置。更重要的是,我如何让它将我的列表传递给视图?

谢谢您的帮助。

编辑....

对困惑感到抱歉。我试图使问题尽可能简单以避免任何混淆。显然,这不起作用:)

我正在.net mvc 项目中实现我自己的会话管理。当请求进入时,我的基本控制器会检查是否在 OnActionExecuting 方法中与请求一起发送了会话 cookie。如果发送了会话 cookie,我的控制器会访问数据库并检索用户的会话信息。会话信息(用户 ID 等)被放入 List 对象并存储在名为“Sess”的属性中。

我希望能够从我的视图中访问 Sess 列表中的元素,如下所示:

那么,我如何以及在哪里让我的控制器将 Sess 列表交给我的视图?

我意识到这不是 .net 中通常实现自定义会话管理的方式。但是,对于我的项目来说,这将是最简单、最干净的解决方案。

感谢迄今为止提供帮助的所有人!

4

4 回答 4

2

一般来说,我建议明确说明您的视图可以访问的内容。因此,我建议您将这些数据从控制器中放入 ViewData,然后将其从视图中拉出 ViewData。这使您的控制器和视图之间的通信线路保持在一个位置并且简单。

但是,如果你真的想从视图中访问 Session,你可以。

<%: ViewContext.HttpContext.Session["key"] %>

您可以做的一件事是拥有自己的从 System.Web.Mvc.ViewPage 派生的自定义视图页面类,并将页面顶部的 Inherits 声明更改为指向您的视图页面。

<%@ Page ... Inherits="YourNamespace.YourViewPage" %>

您的自定义视图页面可以具有您需要的任何属性。

于 2010-04-08T15:50:15.140 回答
0

你必须更好地描述你的问题。

而且,除了动作过滤器或 Controller.OnActionExecuted 覆盖之外,您可以使用Html.RenderAction

于 2010-04-05T18:43:25.997 回答
0

Question not clear: To answer part of it, you can use a property on a base ViewModel. You need to set that property in the constructor of the base ViewModel. Your instance objects need to call the constructor of the base ViewModel explicitly if any values need to be passed down to it for whatever work it is doing... This constructor calling is all normal C# so there are plenty of examples on the web.

I agree that if this is for menus, RenderAction does seem like a much easier way to implement the functionality. I tried the base ViewModel method for menus and then switched to using RenderAction on a controller that is specifically responsible for navigation.

The lack of dynamic navigation examples for ASP.NET MVC sites is surprising as it seems like such a basic requirement.

于 2010-04-05T17:42:54.623 回答
0

为什么不想使用 ViewData?仅仅是因为您不想在每个将一些数据放入 ViewDataDictionary 的操作中都有一行代码吗?

您可以使用操作过滤器并在每个操作执行之前放置该数据,例如

public class AddSomeDataToViewDataAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //filterContext.Controller.ViewData.Add("SomeConstant")(data);
    }
}

然后,您只需将此属性放入每个控制器或基本控制器中。

编辑: 您可以制作几种扩展方法,例如

public static void Add<T>(this IDictionary<string, object> dictionary, T anObject)
{
    var key = typeof(T).Name;
    dictionary.Add(key, anObject);
}

public static T Get<T>(this IDictionary<string, object> dictionary)
{
    var key = typeof(T).Name;
    return (T)dictionary[key];
}

然后像这样添加数据:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    //filterContext.Controller.ViewData.Add<YourListType>(data);
}

在视图中,您将获得如下数据:

ViewData.Get<YourListType>();

问候。

于 2010-04-05T16:49:57.750 回答