0

I have a session in my Login Controller and there i send List of details via Session to the another page.So i need to take one item of the list to show in mvc view(Actially i need to show UserName in my mvc view).

My Controller

    public ActionResult Login(User usrdtl, string returnUrl) 
        {
//some code here
 List<UserDtl> usrList = newsManager.GetUserdetailsByuId(usrdtl.uId);
                        System.Web.HttpContext.Current.Session["UsrSession"] = usrList ;
        }

This usrList consist of lots of user details,i need to show UserName in my view.

In my view i tries to take it as,

<span>@Session["UsrSession"] </span>

But it shows me error

System.Collections.Generic.List`1[NTL.Sys.Entities.UserDtl]

How can i get this ?

TechGuy
  • 4,298
  • 15
  • 56
  • 87
  • Because its a list , you have to iterate the list to fetch the results. You can use LinQ or loops to achieve the same\ – Tushar Gupta Jul 19 '15 at 12:55

1 Answers1

3

It actually does not show you error. It shows the object representation by calling .ToString() on the object.

In your case, Session["UsrSession"].ToString() returns System.Collections.Generic.List1[NTL.Sys.Entities.UserDtl].

Your code actually has no problem at all, modify it to show exactly what you want to show.

I assume that the list contains exactly 1 item. To show the UserName, try:

<span>@((Session["UsrSession"] as List<UserDtl>).First().UserName) </span>

How to show the list is up to you, if you want to display a list of Users, just loop through it. The above code is just an example.

Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • Then it also returns the List know.how to get the UserName from that list client side? – TechGuy Jul 19 '15 at 12:51
  • It shows me error "The Type or namespace name 'UserDtl' could not be found (are you missing a using directive or assembly reference ?" – TechGuy Jul 19 '15 at 12:58
  • @TechGuy: did you have a `using` statement in your view? http://stackoverflow.com/questions/3239006/how-to-import-a-namespace-in-razor-view-page. Try adding `using NTL.Sys.Entities;` – Khanh TO Jul 19 '15 at 12:59
  • @TechGuy: there could be a mistake somewhere with your code. What if you try `Session["UsrSession"] as List` – Khanh TO Jul 19 '15 at 13:04
  • do it but it shows me the previous error "System.Collections.Generic.List`1NTL.Sys.Entities.UserDtl].First().UserName – TechGuy Jul 19 '15 at 13:09
  • @TechGuy: I'm not very familiar with Razor syntax. Try `@((Session["UsrSession"] as List).First().UserName) ` – Khanh TO Jul 19 '15 at 13:11
  • I loop it through that list and do that.thanks for your help to understand the technique. – TechGuy Jul 19 '15 at 13:26
  • What you should be doing is `@((Session["UsrSession"] as List).FirstOrDefault(x => x.UserName) ` – Jamie Rees Jul 19 '15 at 17:38