从asp.net MVC的数据传递给JavaScript的最佳实践 [英] Best practices for passing data from asp.net-mvc to javascript

查看:163
本文介绍了从asp.net MVC的数据传递给JavaScript的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直使用ASP.NET MVC和Javascript / jQuery的很多最近,我似乎在我总是需要通过一些动态值到我的javascript一个方向前进。当脚本就在页面上,我做了这样的事情:

  VAR isEditable =<%=计算机%GT;

我想这是如何快速和放大器;简单,就像我会注入一个值HTML。但这种气味。真的,真的不好。它打破了Visual Studio的IntelliSense和code格式,让我的脚本难以阅读和理解。<​​/ P>

它发生在我的另一个解决方案是将我的数据传递给隐藏字段,并有javascript参考了...

 &LT;输入类型=隐藏ID =编辑VALUE =&LT;%=计算机%GT; /&GT;
VAR isEditable = $(#编辑),ATTR(值)。

这可能是更好的,因为它使脚本完整并允许我把它移动到外部.js文件。但是,一些有关这个解决方案似乎并不理想要么。或者是它只是我吗?

任何人都可以提出解决方案和放大器;数据传递到你的脚本的最佳做法?我是领导错了路,如果我的脚本结束巨资从我的控制器依靠可视数据摆在首位?


解决方案

我有时会通过JSON序列写一个配置对象的页面数据传递给我的网页:

  VAR pageConfig =&LT;%= ServerConfig.ToJson()%取代;

在哪里,你需要自己编写的toJSON方法。这样可以使页面的状态很好的遏制,所以有唯一一个你注入服务器值的地方。从这里走出的一切都是纯JavaScript。在你的榜样,你可以再做:

  VAR isEditable = pageConfig.isEditable;

即使在外部js文件,如果 pageConfig 是全球性的。在这种情况下,虽然,你应该适当的命名空间: MY_APP.pageConfig 也许

I've been working with ASP.NET MVC and Javascript/jQuery a lot lately and I seem to be heading in a direction where I'm always needing to pass some dynamic value "to" my javascript. When the script is right in the page, I've done something like this:

var isEditable = <%=ViewData["editable"]%>

I like how this is quick & easy and just like I'd inject a value into HTML. But this smells. Really, really bad. And it breaks Visual Studio's intellisense and code formatting, making my scripts hard to read and understand.

It has occurred to me another solution would be to pass my data to a hidden field, and have the Javascript reference that...

<input type="hidden" id="editable" value="<%=ViewData["editable"]%>" />
var isEditable = $("#editable").attr("value");

This is probably much better as it keeps the script intact and would allow me to move it to an external .js file. But something about this solution doesn't seem ideal either. Or is it just me?

Can anyone recommend solutions & best practices for passing data into your scripts? Am I headed down the wrong path if my scripts end up heavily relying the viewdata from my controllers in the first place?

解决方案

I sometimes pass data to my pages by writing a config object to the page via a JSON serializer:

var pageConfig = <%= ServerConfig.ToJson() %>;

Where you need to write the ToJson method yourself. This keeps the page state nicely contained, so that there is only one place where you inject server values. Everything from here on out is pure javascript. In your example, you could then do:

var isEditable = pageConfig.isEditable;

even in an external js file, if pageConfig is global. In that case, though, you should properly namespace it: MY_APP.pageConfig perhaps.

这篇关于从asp.net MVC的数据传递给JavaScript的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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