3

On click of an anchor tag the action of my controller is hit. there is a parameter that is passed in query string . I am converting a List to serialized json sting using the below code.

public ActionResult EmployeeVote(string regionID)
 {
   var nomineeList = NomineeModel.GetNomineeByRegionID(Convert.ToInt16(regionID));
   ViewBag.NomineeList = JsonConvert.SerializeObject(nomineeList,Formatting.None);
   return View(ViewBag);
 }

Ths json string I think there is some issue with the way the string is made.

[{"Id":0,"EmpId":1,"FirstName":"First Last","Email":"[email protected]","Description":null,"RegionID":0}]

On client side. But model list is giving error while deserializing it.

$(function () {
            var modelList = JSON.parse('@ViewBag.NomineeList');
           $(modelList).each((function () { //some logic});
 });

I want to perform an each loop to iterate over the model list to create some dynamic element. Any help ??

2
  • 1
    The string [{"Id":0,"EmpId":1,"FirstName":"First Last","Email":"[email protected]","Description":null,"RegionID":0}] is not valid JSON. Commented Feb 14, 2013 at 5:50
  • @MattBall I thought so can you point why the string is wrongly made. Commented Feb 14, 2013 at 5:52

2 Answers 2

5

The problem is that @ViewBag.NomineeList will HTML-encode the json string. You need to prevent this, but still make sure the string is a valid javascript string.

In the controller:

ViewBag.NomineeList = new JavaScriptSerializer().Serialize(
    JsonConvert.SerializeObject(nomineeList, Formatting.None)
    );

The JavaScriptSerializer makes sure that the string is save to be used in JS, so new lines are encoded etc.

Then, in the view:

var modelList = JSON.parse(@Html.Raw(ViewBag.NomineeList));
  • Use Html.Raw to prevent HTML encoding
  • Don't enclose this in quotes as this is already done by JavaScriptSerializer

Update: I added an example how you could make it work without using JavaScriptSerializer. But I reconsidered the potential dangers and I've removed it. Stick to the approach above using JavaScriptSerializer, it's safer.

Sign up to request clarification or add additional context in comments.

Comments

0

Here is an ad hock solution:
Replace the """

ViewBag.NomineeList = JsonConvert.SerializeObject(nomineeList,Formatting.None).Remove(" "");

Also try using http://json.codeplex.com/.

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.