ASP.NET MVC 在 JavaScript 中使用 ViewData

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5863094/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:14:27  来源:igfitidea点击:

ASP.NET MVC using ViewData in javascript

javascriptasp.net-mvc

提问by Jake

I am currently building a website in ASP.NET MVC. I am trying to access ViewData in javascript.

我目前正在 ASP.NET MVC 中构建一个网站。我正在尝试在 javascript 中访问 ViewData。

Is there any way that I can access a string value using javascript in a View that was stored in ViewData in a Controller Action. ( I am not able to figure out the right syntax ).

有什么方法可以在控制器操作中存储在 ViewData 中的视图中使用 javascript 访问字符串值。(我无法找出正确的语法)。

I wish to do something like..

我想做类似的事情..

var str = ViewData["Text"];

I tried the following:

我尝试了以下方法:

var str = <%=ViewData["Text"] %>

var str = <%=ViewData["文本"] %>

but it didn't work.

但它没有用。

Can someone please help.

有人可以帮忙吗。

Thanks.

谢谢。

回答by Darin Dimitrov

Like this (Razor):

像这样(剃刀):

var str = @Html.Raw(Json.Encode(ViewData["Text"]));

or (WebForms), using the JavaScriptSerializer(and after importing theproper namespace to your webform - System.Web.Script.Serialization):

或 (WebForms),使用JavaScriptSerializer(并且在将正确的命名空间导入到您的 webform 之后 - System.Web.Script.Serialization):

var str = <%= new JavaScriptSerializer().Serialize(ViewData["Text"])) %>;

And please don't use ViewData in an ASP.NET MVC application. Use view models and strongly typed views so that your code looks like this:

并且请不要在 ASP.NET MVC 应用程序中使用 ViewData。使用视图模型和强类型视图,使您的代码如下所示:

var str = <%= new JavaScriptSerializer().Serialize(Model.Text) %>;

This technique is even cooler as now you can JSON serialize the entire view model:

这种技术更酷,因为现在您可以 JSON 序列化整个视图模型:

var model = <%= new JavaScriptSerializer().Serialize(Model) %>;
var str = model.Text;

回答by Dave Ward

That should be:

那应该是:

var str = '<%= ViewData["Text"] %>';