-1

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

3
  • 1
    var searchData = JSON.parse(searchDataString.replace(/"/g, '"')); console.log(searchData.SSN);
    – mplungjan
    Commented Jan 30 at 18:07
  • 1
    If by "all the data as a string" you mean it's stored as JSON, then: or var searchData = @Html.Raw(searchDataString); console.log(searchData.SSN) no need to "parse" if it's already JSON. Depends on the format stored.
    – fdomn-m
    Commented Jan 30 at 18:19
  • 1
    Please edit your question to include a sample output - open the page and view source will show you how app = '@Http....' is being rendered - include that here (redact any personal information of course)
    – fdomn-m
    Commented Jan 30 at 18:34

1 Answer 1

1

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);
2
  • If it's already JSON then why set it to a string then parse it? Just set it as an object directly.
    – fdomn-m
    Commented Jan 31 at 8:07
  • @fdomn-m: It needs to be a string to store it in the session. Commented Feb 5 at 16:32

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.