0

Im am developing an MVC 5 App.

I have a UserLoginModel class assigned to a Session Variable.

public class UserLoginModel
{
  public long User_id { get; set; }
  public string Email { get; set; }
  public int Rol_id { get; set; }
  public string Name { get; set; }
  public string LastName { get; set; }
}

private const string SessionKey = "UserLogin";
private readonly HttpContext _httpContext;

public void Save(UserLoginModel user)
{
  _httpContext.Session[SessionKey] = user;
}

I need to get the value of this Session UserLogin.User_id from jQuery. I can Access

var variable = '@Session["UserLogin"]';

But it gives me the value that it is class data type:

UserLoginModel

How can I get a specific value like User_id?

Thanks

1 Answer 1

1

Let's start with session value assignment:

var variable = '@Session["UserLogin"]';

From what I tested, this direct assignment to JS string returned full class name of UserLoginModel. To extract member class values from a stored model class in session variable, you need to declare local variable to hold each member's value in view page with same data type & cast the session as model class name like this:

@{
    long user_id = 0; // local variable to hold User_id value

    // better than using (UserLoginModel)Session["UserLogin"] which prone to NRE
    var userLogin = Session["UserLogin"] as UserLoginModel;

    // avoid NRE by checking against null
    if (userLogin != null)
    {
        user_id = userLogin.User_id;
    }
}

<script type="text/javascript">
    var variable = '@user_id'; // returns '1'
</script>

Note that ViewBag, ViewData & strongly-typed viewmodel using @model directive are more preferred ways over session variable to pass model values into view page.

Live example: .NET Fiddle Demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.