Mykhalik
Mykhalik

Reputation: 244

Deserialize Json in mvc view

In controller I have

 public JsonResult Index()
{
    List<TutorialModel> models = new List<TutorialModel>();
    model.TitleWord = "Go";
    model.Colors = new List<bool>();
    model.Colors.Add(true);
    model.Colors.Add(false);
    model.Colors.Add(false);
    model.Colors.Add(false);
    model.PossibleAnswers = new List<string>();
    model.PossibleAnswers.Add("1");
    model.PossibleAnswers.Add("2");
    model.PossibleAnswers.Add("3");
    model.PossibleAnswers.Add("4");

    string ser = (new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(model);

    return Json(ser, JsonRequestBehavior.AllowGet);
}

And when In view I try to catch this Json result with

<script>
    var values = json.parse(@Model)
</script>

And browser shows me my serialize string. How I can deserialize this json element and store in some variable.

My model for this Controller :

public class TutorialModel
{
    public string TitleWord { get; set; }

    public List<string> PossibleAnswers { get; set; }

    public List<bool> Colors { get; set; }

}

Upvotes: 1

Views: 5838

Answers (2)

johnnycardy
johnnycardy

Reputation: 3046

Note that in your Controller, you don't need to return a JsonResult - unless you're calling it as an ajax method or something. In this case, try returning an ActionResult (or ViewResult) as normal. You could do something like this:

public ActionResult Index()
{
    List<TutorialModel> models = new List<TutorialModel>();
    //...add items to list

    return View(models);
}

Then in your cshtml javascript:

<script>
    var model = @(Html.Raw(Json.Encode(Model)));
<script>

Upvotes: 2

Richard Dalton
Richard Dalton

Reputation: 35793

The problem is that you are returning a JsonResult so all that will be sent to the browser is your JSON, not the view you want.

You need to return a ViewResult:

public ViewResult Index()
{
    List<TutorialModel> models = new List<TutorialModel>();
    model.TitleWord = "Go";
    model.Colors = new List<bool>();
    model.Colors.Add(true);
    model.Colors.Add(false);
    model.Colors.Add(false);
    model.Colors.Add(false);
    model.PossibleAnswers = new List<string>();
    model.PossibleAnswers.Add("1");
    model.PossibleAnswers.Add("2");
    model.PossibleAnswers.Add("3");
    model.PossibleAnswers.Add("4");

    string ser = (new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(model);

    return View("Index", ser);
}

Then in your view you can have:

<script>
   var values = JSON.parse("@Model")
</script>

Upvotes: 0

Related Questions