Javascript 在视图中将 .Net 对象转换为 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8502146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert .Net object to JSON object in the view
提问by Jayantha Lal Sirisena
I want to convert a .Net object in to JSON in the view. My view model is like this,
我想在视图中将 .Net 对象转换为 JSON。我的视图模型是这样的,
public class ViewModel{
public SearchResult SearchResult { get; set;}
}
public class SearchResult {
public int Id { get; set; }
public string Text{ get; set; }
}
I want to convert Model.SearchResult
in to a JSON object. Currenty I'm doing it like this:
我想转换成Model.SearchResult
JSON 对象。目前我正在这样做:
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
//....
var s = @serializer.Serialize(Model.Institution);
but the result is like this,
但结果是这样的
var s = { "Name":"a","Id":1};
Create:228Uncaught SyntaxError: Unexpected token &
How can I convert this correctly in to a JSON object?
如何将其正确转换为 JSON 对象?
回答by Kyeotic
Try using this method:
尝试使用此方法:
@Html.Raw(Json.Encode(Model.Content))
@Html.Raw(Json.Encode(Model.Content))
回答by Loic El Thesea
I use this helper since asp.net mvc 2
我从 asp.net mvc 2 开始使用这个助手
public static MvcHtmlString ToJson(this HtmlHelper html, object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return MvcHtmlString.Create(serializer.Serialize(obj));
}
public static MvcHtmlString ToJson(this HtmlHelper html, object obj, int recursionDepth)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RecursionLimit = recursionDepth;
return MvcHtmlString.Create(serializer.Serialize(obj));
}
And in the view:
在视图中:
<script>
var s = @(Html.ToJson(Model.Content));
</script>
I should replace serializer with the JSON.Encode(..) now, like mentionned in the refer by Hemant. (It use itself JavaScriptSerializer).
我现在应该用 JSON.Encode(..) 替换序列化器,就像 Hemant 在引用中提到的那样。(它使用自己的 JavaScriptSerializer)。
The source of your problem is the "@" which HTML encode the JSON. You can use @Html.Raw(..) to avoid this behavior.
您的问题的根源是 HTML 对 JSON 进行编码的“@”。您可以使用 @Html.Raw(..) 来避免这种行为。
+: take a look for Json.Net http://json.codeplex.com/
+:查看 Json.Net http://json.codeplex.com/
JSON.Net update
JSON.Net 更新
I've updated the helper a while ago with JSON.net (much better).
不久前我用 JSON.net 更新了助手(好多了)。
It seems some users continue to read, upvote and use the old code. I'd like they use a better way, with the new version below, or by using NGonlike Matthew Nicholshas noticed it in a comment.
似乎有些用户继续阅读、投票和使用旧代码。我希望他们使用更好的方法,使用下面的新版本,或者像Matthew Nichols在评论中注意到的那样使用NGon。
Here's the code:
这是代码:
using System;
using Newtonsoft.Json;
namespace System.Web.Mvc
{
public static class HtmlHelperExtensions
{
private static readonly JsonSerializerSettings settings;
static HtmlHelperExtensions()
{
settings = new JsonSerializerSettings();
// CamelCase: "MyProperty" will become "myProperty"
settings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
}
public static MvcHtmlString ToJson(this HtmlHelper html, object value)
{
return MvcHtmlString.Create(JsonConvert.SerializeObject(value, Formatting.None, settings));
}
}
}
回答by Clarence
This is an update to my original answer and I'll admit that as a result of the insistent badgering of @Tyrsius :D who refused to give up the fact that I could not access vars created in <script>
tags in my MVC 5 cshtml page from my .js libraries in separate files, I discovered that if I placed the script tags inside of the @section scripts statement block that the vars created there did make the global scope and was available to my plugin widgets. I have not used it within any of my more complex apps as of yet, but did use it in a protoType of another app and the answer is below. Now @Html.Raw(...) works and I was able to serialize an object that I could immediately use.
这是对我的原始答案的更新,我承认,由于 @Tyrsius :D 的顽固纠缠,他拒绝放弃我无法<script>
从我的 MVC 5 cshtml 页面中访问在标签中创建的变量的事实.js 库在单独的文件中,我发现如果我将脚本标记放在 @section scripts 语句块中,那么在那里创建的 vars 确实会形成全局范围并且可用于我的插件小部件。到目前为止,我还没有在任何更复杂的应用程序中使用它,但确实在另一个应用程序的原型中使用了它,答案如下。现在@Html.Raw(...) 工作,我能够序列化一个我可以立即使用的对象。
This is something I will be using from now on... thanks again for hanging in there with me @Tyrsius
这是我将从现在开始使用的东西......再次感谢你和我在一起@Tyrsius
@section scripts
{
<script type="text/javascript">
@using MRTCProtoType.Models.ControllerData.Contracts
var testVar = @Html.Raw(JsonConvert.SerializeObject(WMMWorkloadTestData.getWorkloadTestData()));
</script>
@Scripts.Render("~/bundles/homeworkflow")
}
The following code is in a separate .js file
以下代码位于单独的 .js 文件中
$(document).ready(function() {
alert(JSON.stringify(testVar));
});