较好地解决了在JavaScript code。使用Url.Action [英] Better solution to using Url.Action in javascript code

查看:200
本文介绍了较好地解决了在JavaScript code。使用Url.Action的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用asp.net MVC 3(用剃刀)我当前的项目,当我做Ajax调用,我必须保持在JS视图页面上,因为我想用Url.Action生成的URL。这意味着我不能出去分裂JS code到.js文件,难道还有比我目前正在做的事情更好的解决方案。

In my current project using asp.net MVC 3 (using razor), when I'm making Ajax calls, I have to keep the JS on the view page because I want to use Url.Action to generate the URL. This means I can't split the js code out into .JS files, Is there a better solution than what I'm currently doing.

推荐答案

我倾向于,因为我喜欢我的命名空间中的JavaScript类似的方式如上做到这一点,一个稍微不同的扭曲。

I tend to accomplish this in a similar way as above, with a slightly different twist as I like namespacing my javascript.

JavaScript文件看起来是这样的:

The javascript file looks something like:

var my = {};

my.viewname = 
{
   init : function(settings){
      // do some work here. settings.someImportantUrl has my json/ajax url eg.
      alert(settings.someImportantUrl );
   }
}

然后,我的观点将包含类似:

Then my view would contain something like:

<script language='javascript'>
  // allocate an object with variables you want to use in the external js file
  var settings = {someImportantUrl: '<%=Url.Action(...)%>'};
  // call an init method for the current view
  my.viewname.init(settings);
</script>

这篇关于较好地解决了在JavaScript code。使用Url.Action的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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