通过服务器端MVC变量的JavaScript [英] passing server side mvc variables to javascript

查看:124
本文介绍了通过服务器端MVC变量的JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在看反馈,从控制器动作网站HTML标记通过服务器端变量的最好和最简单的方式对它们进行再由JavaScript的网站上使用。

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.

我用asp.net mvc4工作,并试图找到做这样的推荐方法。

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

推荐答案

您有几个选项。

一是重视数据的属性或ID对元素和使用JavaScript获取它们。

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

使用剃须刀的观点:

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

JS:

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

或者你也可以直接呈现数据插入脚本代码。

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

使用剃刀:

 var somevar = "@item"

您也可以Json.En code更复杂的对象。

You can also Json.Encode more complex objects.

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

这篇关于通过服务器端MVC变量的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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