How to Persist data using session variable in mvc3 razor view?

故事扮演 提交于 2019-12-21 12:06:52

问题


I am working in MVC3 Application with Razor. In my Account controller after validating the user, i am getting the user ClientID from Database. Here i want to persist ClientID in Session variable. which was using across the all controller and Razor view.

I have no idea as to what is the best way to implement this.OR How to persist data in the session variable. And how to use persisted data in the session variable in across the controller.

Thanks for your help..


回答1:


If you are using ASP.NET Forms Authentication, the user name is already stored in a cookie. You can access it from the Controller via

Controller.User.Identity.Name

It's possible to store the user ID as the user name. When you call something like

FormsAuthentication.RedirectFromLoginPage

Give it the ID instead of a name. The ID can then be found using the method above and no extra session data is necessary. If you want to store something in the session, just call

Session["UserID"] = value;

From your controller.




回答2:


I usually write a Session wrapper that allows me easy access to it in the future:

public class SessionData
{
    const string ClientId_KEY = "ClientId";

    public static int ClientId
    {
        get { return HttpContext.Current.Session[ClientId_KEY] != null ? (int)HttpContext.Current.Session[ClientId_KEY] : 0; }
        set { HttpContext.Current.Session[ClientId_KEY] = value; }
    }
}

After that you can access it from anywhere like this:

int clientId = SessionData.ClientId;

If you want you can use whole objects in Session like this.

Or you can set it like so: SessionData.ClientId = clientId;



来源:https://stackoverflow.com/questions/11643721/how-to-persist-data-using-session-variable-in-mvc3-razor-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!