ASP.NET MVC - Pass Json String to View using ViewData
Asked Answered
T

1

14

I'm trying to pass Json to my View using ViewData

Controller

ViewData("JsonRegionList") = Json(RegionService.GetActiveRegions())

view

        $("input#UserRegion").autocomplete({
                source:"<%: ViewData("JsonRegionList").ToString %>",
                minLength: 3,

but the problem I'm running into is the output source looks like

        $("input#UserRegion").autocomplete({
                source:"System.Web.Mvc.JsonResult",
                minLength: 3,

which is obviously not right. Am I missing something basic?

Tonguing answered 26/7, 2010 at 2:9 Comment(0)
F
19

The Json() controller method returns a JsonResult, which isn't the same as a JSON string. The JsonResult holds data, but the data is actually written directly to the response when the View Engine calls JsonResult.ExecuteResult(). That's all probably more information than you want there - the point is that calling Json() in a controller won't give you a string of JSON.

If you just want to turn your data into a JSON string, you can use the JavaScriptSerializer, which is what the Json() method uses internally:

JavaScriptSerializer serializer = new JavaScriptSerializer();
ViewData["JsonRegionList"] = serializer.Serialize(jsonRegionList); 
Flaunch answered 26/7, 2010 at 4:57 Comment(3)
JavaScriptSerializer is not Defined. Do I need to reference another assembly?Tonguing
looks as though I had to add the System.Web.Extensions assembly to my project... testing now.Tonguing
The namespace should be System.Web.Script.Serialization and you would serialize your RegionService.GetActiveRegions()Picky

© 2022 - 2024 — McMap. All rights reserved.