0

I'm filling values to a session's like following to retrive those in _LayoutPartial view

if (userdata != null)
{
    Session["userdata"] = new SampleViewModel { FirstName = userdata.UserFirstName, LastName = userdata.UserLastName };
    FormsAuthentication.SetAuthCookie(loginmodel.UserName, false);
    return RedirectToAction("Dashboard", "Home", new { username = loginmodel.UserName });
}

I want to retrive those values in _LayoutPartial View , So I tried somethin like following

<a class="sa">
    (@Session["userdata"] as ProjectName.Models.SampleViewModel).FirstName 
    (@Session["userdata"] as ProjectName.Models.SampleViewModel).LastName
</a>

But this is not retrieving data properly . In this _LoginPartial I'm not Referencing any model also

1 Answer 1

1

You have your parenthesis in the wrong spot, and you need a double set - one for the casting (inner set) and one for the razor execution (outer set). It needs to be

@((Session["userdata"] as ProjectName.Models.SampleViewModel).Name)
Sign up to request clarification or add additional context in comments.

4 Comments

Is that the my approach optimum way , show the user.FirstName , user.LastName on _LayoutPartial if I'm not following any membership providers
Personally I would have a base view model that is used in the view and I would be adding the values to the FormAuthenticationTicket, rather than using Session, but there is nothing wrong with what your doing
If this @((Session["userdata"] as ProjectName.Models.SampleViewModel).Name) getting null , when view loading then run time error is occurring , how to avoid that and store this inside a variable to reuse easily ?
You need to check for null first - e.g. @{ var userData = Session["userdata"] as ProjectName.Models.SampleViewModel; } then @if(userData != null} { <a class="sa">@userData.FirstName @userData.FirstName</a> }

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.