ASP.NET MVC - 通JSON字符串查看使用的ViewData [英] ASP.NET MVC - Pass Json String to View using ViewData
问题描述
我试图传递的Json用的ViewData我查看
I'm trying to pass Json to my View using ViewData
控制器
ViewData("JsonRegionList") = Json(RegionService.GetActiveRegions())
查看
$("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?
推荐答案
的JSON()控制器方法返回一个JsonResult,这是不一样的JSON字符串。该JsonResult保存数据,但数据实际上是直接写入到响应时,视图引擎调用JsonResult.ExecuteResult()。这是所有可能的更多信息比你想有 - 点是,在一个控制器调用JSON()不会给你的JSON字符串
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.
如果你只是想将您的数据转换成JSON字符串,可以使用的JavaScriptSerializer,这是什么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);
这篇关于ASP.NET MVC - 通JSON字符串查看使用的ViewData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!