Search code examples
asp.net-mvcentity-frameworklinqaspnetcoretemplatepack

How can can i read values from linq query in AspNetCore?


var userData = from x in _context.UserAccount.Where(x => x.UserName == login.UserName)
                                    select new { x.UserFullName, x.Email, x.UserAddress ,x.UserName
                                    ,x.UserPhoto ,x.UserMobileNo,x.UserGender,x.UserQualification,
                                    x.UserDepartment,x.UserDesignation,x.UserPriviledge,x.UserAccountId};

TempData["userData"] = JsonConvert.SerializeObject(userData);

How can I read values from userData? and then store in TempData to pass on to the next view? Please Help! Thank you!!


Solution

  • You should create UserViewModel like below

    public class UserViewModel
    {
        public string UserFullName {get; set; }
        public string Email {get; set; }
        public string UserAddress {get; set; }
        // The rest of properties
    }
    

    Then you can select the result like this

    var userData = (from x in _context.UserAccount.Where(x => x.UserName == login.UserName)
                        select new UserViewModel 
                        { 
                            UserFullName =  x.UserFullName,
                            Email = x.Email, 
                            UserAddress = x.UserAddress 
                            // The rest of properties 
                        }).ToList();
    TempData["userData"] = userData;
    

    Finally, in View you can get like this

    @{
      var userData = TempData["userData"] as List<UserViewModel>; // Make sure you've already included _NameSpace_Of_UserViewModel
    }