Json序列化:如何将C#数据发送到javascript脚本.错误:无效字符 [英] Json serialization: how to send c# data to javascript script. Error: Invalid character
问题描述
我正在尝试将数据从Entity Framework数据库发送到网页上的js脚本.这是我的MVC控制器:
I'm trying to send data from Entity Framework database to js script on my webpage. This is my MVC Controller:
public ActionResult Index()
{
var wordsToShow = db.Words.Where(w => w.OwnerName == User.Identity.Name); // && DateTime.Compare(w.NextReview, DateTime.Now) <= 0
ViewBag.wordsToShow = HttpUtility.HtmlDecode(new JavaScriptSerializer().Serialize(wordsToShow));
var test = ViewBag.wordsToShow;
return View();
}
在index.cshtml中,我输入了以下代码:
And in index.cshtml I've put this code:
<script>
var wordsJson = "@ViewBag.wordsToShow.ToString()";
var wordsAsObject = JSON.parse(wordsJson);
</script>
问题是,javascript说:
The problem is, javascript says:
无效字符
在我将json解析为javascript对象的行中.原因是:json字符串看起来不应该.这是Web浏览器中"wordsJson"变量内部的一部分:
In the line where I'm parsing json to javascript object. The reason is: json string doesn't look like it should. This is part of what's inside "wordsJson" variable in web browser:
我该怎么做才能使其正常工作?
What can I do to make it work?
推荐答案
您正在以一种过度回旋的方式进行操作.出于某种原因,JSON被称为"JavaScript对象表示法".无需将其放在字符串中并重新解析.您可以只使用JSON as JavaScript.
You're going about in an overly roundabout way. JSON is called "JavaScript Object Notation" for a reason. There's no need to put it in a string and re-parse it. You can just use the JSON as JavaScript.
ASP.NET MVC有一个用于将值序列化为JSON的助手,因此您可以使用它并将其分配给JavaScript中的变量:
ASP.NET MVC has a helper for serializing values as JSON, so you can just use that and assign it to a variable in your JavaScript:
<script>
var wordsAsObject = @Html.Raw(Json.Encode(ViewBag.wordsToShow));
</script>
这将消除在Action中进行JSON序列化的需要.
This would eliminate the need to do the JSON serialization within your Action.
我怀疑您遇到此问题的原因是,默认情况下,使用@
插入到视图中的值会自动进行HTML编码.您可以使用Html.Raw()
来防止这种情况发生,就像我在上面所做的那样,但是正如我所说的,没有理由先将其放入字符串并进行解析.
I suspect that the reason you're encountering this issue is that by default, values inserted into a view with @
are automatically HTML encoded. You can use Html.Raw()
to prevent this, as I've done above, but as I said, there's no reason to put it into a string first and parse it.
这篇关于Json序列化:如何将C#数据发送到javascript脚本.错误:无效字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!