Minh Triet
Minh Triet

Reputation: 1250

Access JSON returned by Controller in View

I am trying to serialize my linq to JSON. My issue is Json result wrapped in pre tag - how to get value of it. The answer is not what I am looking for though. Here are my code Controller

return Json(regionBoudaries, JsonRequestBehavior.AllowGet);

I see that my JSON string is written in the page Now I am writing something like something like

View

$(document).ready(function () {        
    initialize(); 
    process(a_variable);
}

How can I set the a_variable the value of the JSon returned from controller. Please help me out. Thank you in advance

Upvotes: 1

Views: 255

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

You could use a view model:

public class MyViewModel
{
    public class SomeType RegionBoudaries { get; set; }

    ... some other properties
}

and then have the controller action serving this view populate the property of the view model:

public ActionResult SomeAction()
{
    var model = new MyViewModel();
    model.RegionBoudaries = ... same stuff as in your other action
    return View(model);
}

and then in the corresponding strongly typed view:

@model MyViewModel
...
<script type="text/javascript">
    $(document).ready(function () {        
        var a_variable = @Html.Raw(Json.Encode(Model.RegionBoudaries));
        initialize(); 
        process(a_variable);
    });
</script>

Upvotes: 1

Related Questions