Hallo guys,

喂,

I'm using ASP.NET MVC with jquery and it's going great for now. Just, there is one question that is bothering me. How should I handle urls in jquery methods? I really wouldn't like to hard code it, like here:

我用ASP。NET MVC带有jquery,现在运行得很好。只是,有一个问题困扰着我。如何处理jquery方法中的url ?我真的不喜欢硬编码,比如这里:

 $(function() {  
        $.getJSON("/Home/List", function(data) {  
            var items = "---------------------";  
            $.each(data, function(i, country) {  
                items += "" + country.Text + "";  
            });  
            $("#Countries").html(items);  
        });  

       $("#Countries").change(function() {  
           $.getJSON("/Home/States/List/" + $("#Countries > option:selected").attr("value"), function(data) {  
               var items = "---------------------";  
               $.each(data, function(i, state) {  
                   items += "" + state.Text + "";  
               });  
               $("#States").html(items);  
           });  
       });  
   });  

It is highly recommended to use HTML helper methods to create links in MVC, like Html.ActionLink, Html.BeginForm so in case that someone change that HomeController is mapped on MyHome instead of Home there will be no problem.

强烈建议使用HTML helper方法在MVC中创建链接,如HTML。ActionLink,Html。如果有人更改HomeController被映射到MyHome而不是Home,那么BeginForm就没有问题了。

So, how not to hard code the url like in example?

那么,如何不像示例那样硬编码url呢?

Also, I don't want to use ASP.NET Ajax because i agree with this answer asp-net-ajax-vs-jquery-in-asp-net-mvc.

另外,我不想使用ASP。NET Ajax,因为我同意这个答案。

Thanks

谢谢

3 个解决方案

#1


6

You could define multiple global javascript variables:

您可以定义多个全局javascript变量:

<script type="text/javascript">
    var listUrl = '<%= Url.Action("Index", "Home") %>';
    var statesListUrl = '<%= Url.Action("States", "Home") %>';
</script>

which will be used later by the $.getJSON methods.

这将在后面用$。getJSON方法。

更多相关文章

  1. 有什么方法可以让jQuery循环在到达终点或开始时不循环?
  2. js限制文本框只能输入数字方法
  3. html 页面内锚点定位及跳转方法总结
  4. 是否有更快的方法来遍历HTMLDocument中的每一个元素呢?
  5. Jquery-如何使用prop方法更改backgroundColor?
  6. 关于 客户端发现响应内容类型为“text/html; charset=utf-8”,但
  7. HTML5 Canvas 绘图方法整理 【十五、Canvas页面交互: 鼠标事件 】
  8. 不会出现Javascript context.closePath()方法
  9. Delphi下发送Email的方法

随机推荐

  1. 编写自己的代码库(javascript常用实例的实
  2. 【9.0】对于java集合的迭代器的底层分析
  3. GenericObjectPool对象池异常排查
  4. Java的HelloWorld程序的真正用法
  5. Java普通代码块,构造代码块,静态代码块区别
  6. Java操作数据库之jdbc【原生方式】
  7. java数据结构--链表
  8. 读阿里巴巴Java开发手册v1.2.0之工程结构
  9. Ubuntu12 64位 阿里云服务器端配置mysql+
  10. 记一次java内存分析