ASP.NET MVC - 使用 ViewData 将 Json 字符串传递给视图
我正在尝试使用 ViewData
Controller
ViewData("JsonRegionList") = Json(RegionService.GetActiveRegions())
view
$("input#UserRegion").autocomplete({
source:"<%: ViewData("JsonRegionList").ToString %>",
minLength: 3,
将 Json 传递到我的视图,但我遇到的问题是输出源看起来
$("input#UserRegion").autocomplete({
source:"System.Web.Mvc.JsonResult",
minLength: 3,
显然不正确。我错过了一些基本的东西吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Json() 控制器方法返回 JsonResult,它与 JSON 字符串不同。 JsonResult 保存数据,但当视图引擎调用 JsonResult.ExecuteResult() 时,数据实际上直接写入响应。这可能比您想要的更多信息 - 重点是在控制器中调用 Json() 不会为您提供 JSON 字符串。
如果您只想将数据转换为 JSON 字符串,则可以使用 JavaScriptSerializer,这是 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.
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: