C# 如何在 JavaScript 中访问 ViewData
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2374707/
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
How to Access ViewData in javascript
提问by Billy Logan
I am having a problem accessing the ViewData object through javascript.
我在通过 javascript 访问 ViewData 对象时遇到问题。
I have set the ViewData object on the controller and on document.ready event of the view i am trying to see the contents of that same ViewData object like so:
我已经在控制器和视图的 document.ready 事件上设置了 ViewData 对象,我试图查看同一个 ViewData 对象的内容,如下所示:
var test = <%= ViewData["NAME"].ToString() %>;
alert(test);
I don't get an alert message after this and none of my script after this statement will run. I am assuming this script is invalid thus killing everything afterwards. I have tried a few different variations of this same script without any luck.
在此之后我没有收到警报消息,并且在此语句之后我的脚本都不会运行。我假设此脚本无效,因此之后会杀死所有内容。我尝试了相同脚本的几种不同变体,但没有任何运气。
What am i missing here?
我在这里错过了什么?
Thanks in advance, Billy
提前致谢,比利
采纳答案by John Rasch
Try adding some quotes around the output:
尝试在输出周围添加一些引号:
var test = '<%= ViewData["NAME"].ToString() %>';
alert(test);
Edit:
编辑:
I notice you're using NAME
for the key; could this name ever have a single quote in it? If it's possible that any value will ever contain one, you will want something like this instead so your page doesn't break again (although technically this seems to be more of a job for the controller or model):
我注意到您正在使用NAME
密钥;这个名字可以有单引号吗?如果任何值都可能包含一个,您将需要这样的东西,这样您的页面就不会再次中断(尽管从技术上讲,这似乎更像是控制器或模型的工作):
var test = '<%= ViewData["NAME"].ToString().Replace("'", "\'") %>';
alert(test);
回答by Marek Karbarz
try
尝试
var test = '<%= ViewData["NAME"].ToString() %>';
alert(test);
(notice the quotes around <%= %>
)
(注意周围的引号<%= %>
)