javascript - 在 javascript 代码中使用 Url.Action 的更好解决方案

标签 javascript asp.net asp.net-mvc

在我当前使用asp.net MVC 3(使用razor)的项目中,当我进行Ajax调用时,我必须将JS保留在 View 页面上,因为我想使用Url.Action来生成URL。这意味着我无法将 js 代码拆分为 .JS 文件,是否有比我目前正在做的更好的解决方案。

最佳答案

我倾向于以与上面类似的方式来完成此任务,但略有不同,因为我喜欢为 javascript 命名空间。

JavaScript 文件看起来像:

var my = {};

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

然后我的 View 将包含类似以下内容:

<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 - 在 javascript 代码中使用 Url.Action 的更好解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4781552/

相关文章:

javascript - 从 .env 文件访问 .pem 公钥

php - 将用户重定向到登录页面,而不在 Facebook 页面上使用 fbml

c# - ASP.NET MVC5 自定义 AuthorizeAttribute 未被正确调用

带有 jQ​​uery SimpleModal 和 Ajax.BeginForm Helper 的 ASP.NET MVC

c# - 返回类型为 IEnumerable 而不仅仅是 List?

javascript - 带滚动条的推送菜单

javascript - domstyle.set 在 dojo 中不起作用

c# - 无法加载文件或程序集 'MySql.Data, Version=6.9.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' 或其依赖项之一

asp.net - 如何修改 web.config 以不重写某个 url?

asp.net - 当redirectMode = ResponseRewrite 时,为什么 HttpContext.Session 为 null