javascriptc#jqueryasp.net-mvc

Get Session Model from webpage using jquery


I am doing an MVC 6 App. I have a model like this

public class SearchModel 
{
    public string SSN { get; set; } = string.Empty;
    public string EmployeeNumber { get; set; } = string.Empty;
    public string LastName { get; set; } = string.Empty;
    public string FirstName { get; set; } = string.Empty;
}

And I have it stored in a Session called SearchData

I need to see the data stored from chtml page. I have this

 $(document).ready(function () {
     var app = '@HttpContextAccessor?.HttpContext?.Session?.GetString("SearchData")';
 });

But it returns all the data as a string.

How can I get specific field? like SSN or EmployerName? Do I have to parse it into Json Model?

Thanks


Solution

  • You need to convert it to a JSON string and store it that way.

    var json = new JavaScriptSerializer().Serialize(searchData);
    

    Store that in the session and then parse it when you pull it out:

    const searchDataJson = '@HttpContextAccessor?.HttpContext?.Session?.GetString("SearchData")';
    const searchData = JSON.parse(searchDataJson);