如何在 JavaScript 中访问 ViewData [英] How to Access ViewData in javascript

查看:24
本文介绍了如何在 JavaScript 中访问 ViewData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在通过 javascript 访问 ViewData 对象时遇到问题.

I am having a problem accessing the ViewData object through javascript.

我已经在控制器和视图的 document.ready 事件上设置了 ViewData 对象,我试图像这样查看同一个 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:

     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.

我在这里遗漏了什么?

提前致谢,比利

推荐答案

尝试在输出周围添加一些引号:

Try adding some quotes around the output:

var test = '<%= ViewData["NAME"].ToString() %>';
alert(test);

我注意到您使用 NAME 作为密钥;这个名字可以有单引号吗?如果任何值都可能包含一个值,那么您会想要这样的东西,这样您的页面就不会再次中断(尽管从技术上讲,这似乎更像是控制器或模型的工作):

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):

var test = '<%= ViewData["NAME"].ToString().Replace("'", "\'") %>';
alert(test);

这篇关于如何在 JavaScript 中访问 ViewData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆