【问题标题】:Redirect to controller using JavaScript and MVC使用 JavaScript 和 MVC 重定向到控制器
【发布时间】:2012-11-07 08:31:27
【问题描述】:

我正在尝试使用这行代码从 JavaScript 重定向到控制器

 location.href = '/Dashboard/';

它重定向到仪表板,但在我的仪表板视图中,当文档加载时调用此方法

 $.post("Dashboard/UsersGet", {}, function (dataSet) {
    //do something with the dataset
 }); 

然后我得到这个错误。

POST http://localhost:1414/Dashboard/Dashboard/UsersGet 404 (Not Found) 

我可以看到仪表板被添加到 url 中两次。如何在不发生这种情况的情况下重定向到控制器?

【问题讨论】:

    标签: javascript asp.net-mvc model-view-controller


    【解决方案1】:

    使用Url 助手:

    @Url.Action("UsersGet", "Dashboard")
    

    完整代码:

    $.post('@Url.Action("UsersGet", "Dashboard")', {}, function (dataSet) {
        //do something with the dataset
     });    
    

    Asp .Net MVC 中的路由不像经典的 Asp.Net 那样工作。

    【讨论】:

    • 感谢@gdoron,但请您详细说明为什么我应该使用 Url.Action 而不是添加正斜杠 :)
    • @JohandeKlerk。你知道路线是如何运作的吗?它们可以定制,Url 助手知道如何处理它们。在 asp.net 中没有这样的东西。无论如何,在 MVC 中,您使用的是动作和控件,而不是 URL。 Read more here
    【解决方案2】:

    试试这个:

     $.post("/Dashboard/UsersGet", {}, function (dataSet) {
        //do something with the dataset
     }); 
    

    在网址中添加/

    【讨论】:

      【解决方案3】:
       $.post("Dashboard/UsersGet", {}, function (dataSet) {
          //do something with the dataset
       }); 
      

      应该是

       $.post("/Dashboard/UsersGet", {}, function (dataSet) {
          //do something with the dataset
       }); 
      

      如果没有'/',您发布的网址将附加到当前网址。

      【讨论】:

        猜你喜欢
        • 2016-10-06
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        • 2015-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多