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

北战南征 提交于 2019-12-18 12:23: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?


回答1:


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); 


来源:https://stackoverflow.com/questions/3331842/asp-net-mvc-pass-json-string-to-view-using-viewdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!