将服务器端 mvc 变量传递给 javascript

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

passing server side mvc variables to javascript

javascriptasp.net-mvcasp.net-mvc-4

提问by amateur

I am looking at feedback as to the best and easiest way to pass server side variables from a controller action to the sites html markup and for them to be used then by javascript on the site.

我正在查看有关将服务器端变量从控制器操作传递到站点 html 标记的最佳和最简单方法的反馈,然后由站点上的 javascript 使用它们。

I am working with asp.net mvc4 and trying to find the recommended method of doing such.

我正在使用 asp.net mvc4 并试图找到推荐的方法。

回答by Declan Cook

You have a couple of options.

你有几个选择。

One is attach data-attributes or id's to elements and fetch them using javascript.

一种是将数据属性或 id 附加到元素并使用 javascript 获取它们。

Using razor views:

使用剃刀视图:

<div id="someid" data-name="@item.attribute"></div>

JS:

JS:

$('#someid').data('name')

Or you can render the data directly into a script tag.

或者您可以将数据直接渲染到脚本标记中。

Using razor:

使用剃须刀:

 var somevar = "@item"

You can also Json.Encode more complex objects.

您还可以 Json.Encode 更复杂的对象。

 var somevar = @Html.Raw(Json.Encode(object))