0

I have a JSON string returned from my asp.net mvc3 application controller using viewbag key as below, depending on various scenarios it can be null too

{"Name":"TShirt","Id":"85","Gender":"M","Size":"Medium"}

and I am trying to assign this JSON object to my local anonymous variable as shown below:

    var data = '@ViewBag.UserData'; 

The above ViewBag is null on initial page load, but as the user keys in the criteria, I store this into a session variable. Whenever user selects a product and clicks on back to previous page link, I restore these filters froms session and place them in Viewbag for further processing on the View.

This is working perfectly fine when user clicks back to previous page , but I see a script error on the initial load because the var data = '@ViewBag.UserData'; evaluates to var data = ;

I tried the below too but am still seeing the error

var data = '@ViewBag.UserData' != '' ? @Html.Raw(@ViewBag.UserData): {};

I tried

var data = '@ViewBag.UserData' != '' ? '@Html.Raw(@ViewBag.UserData)': {};

but I am unable to parse the data that I get in the back to previous page scenario. Am I doing something wrong here?

6
  • If you do @ViewBag.UserData without quotes when using ternary? Commented Jan 13, 2015 at 7:23
  • it evaluates to something like this and still a script error var data = '' != '' ? : {}; Commented Jan 13, 2015 at 7:24
  • you used @Html.Raw with quotes there? try both wihout? Commented Jan 13, 2015 at 7:26
  • the above comment output is for var data = '@ViewBag.UserData' != '' ? @Html.Raw(@ViewBag.UserData): {}; Commented Jan 13, 2015 at 7:27
  • var data = '@(ViewBag.UserData ?? Html.Raw(""))'; Commented Jan 13, 2015 at 7:27

2 Answers 2

1

I am not so clear that what you really wanted. But as per my understanding, I think you are looking for JSON parser.

var str = '{"one":"1","two":"2"}';
console.log(str); // Prints string
var obj = JSON.parse(str); //Converts string to JSON object
console.log(obj); // Prints JSON object
Sign up to request clarification or add additional context in comments.

1 Comment

Rama Rao, exactly what I wanted. I tried $.parseJson but it didnt work, so I thought parsing isn't the right approach. I must have done a mistake while trying to parse
0

You can try replace '' to null or {} . May be the code works.

var data = '@ViewBag.UserData' != **null or {}** ? '@Html.Raw(@ViewBag.UserData)': {};

Comments

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.