简体   繁体   English

如何创建一个将在asp.net mvc中返回当前PageData的包装器?

[英]how to create a wrapper that will return the current PageData in asp.net mvc?

i want to create a wrapper class that will let me use PageData as it was a strongly typed class. 我想创建一个包装类,让我使用PageData,因为它是一个强类型类。
i used this method before in asp.net using HttpContext.Current.Session to define all the items i can store in the session and all the manipulation of the session was done through that class. 我之前在asp.net中使用此方法使用HttpContext.Current.Session来定义我可以存储在会话中的所有项目,并且会话的所有操作都是通过该类完成的。
example

namespace app.Web
{
    public static class Session
    {
        public string UserName
        {
        get { return HttpContext.Current.Session["UserName"] as string; }
        set { HttpContext.Current.Session["UserName"] = value; }
        }
        ...........
    }
}

i want to know how to get the Pagedata in a similar way. 我想知道如何以类似的方式获取Pagedata。

PageData is only available within the page itself, not available anywhere else (like the controller). PageData仅在页面本身可用,在其他任何地方都不可用(如控制器)。 The best way to do this is with extension methods. 执行此操作的最佳方法是使用扩展方法。

Frederik Vig wrote a blog post showing how this might be done. Frederik Vig撰写了一篇博客文章,展示了如何做到这一点。

Example: 例:

namespace PageData.Extensions
{
    public static partial class PageDataExtensions
    {
        public static string UserName(this PageData page)
        {
            return page["UserName"] as string;
        }
    }
}

BTW, you can use the same method for Session as well, which might be cleaner than the method you propose. 顺便说一句,你也可以使用相同的Session方法,这可能比你提出的方法更清晰。

Edit: 编辑:

Based on your comments, there are several other options. 根据您的意见,还有其他几种选择。

  1. Create your data as a class and add that class as an extension. 将您的数据创建为类,并将该类添加为扩展名。 ie Like above, but make it PageData.Utils.UserName this way it adds only a single item to the PageData intellisense and doesn't clutter it too much, and allows you to filter out the PageData methods from extension methods. 就像上面一样,但是以这种方式使它成为PageData.Utils.UserName ,它只向PageData intellisense添加一个项目,并且不会使它过多混乱,并允许您从扩展方法中过滤出PageData方法。
  2. Create your static class just like you want to, but use methods instead of properties. 像你想的那样创建静态类,但使用方法而不是属性。

Example: 例:

public static class Utils
{
    public static string UserName(IDictionary<object,dynamic> pageData) {
        return pageData["UserName"] as string;
    }
}

Then in your code just do this (assuming you have the proper @using statements in your view): 然后在您的代码中执行此操作(假设您在视图中有正确的@using语句):

@Utils.UserName(PageData)

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

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