【问题标题】:How to implement another var parameter name for the route如何为路由实现另一个 var 参数名称
【发布时间】:2013-08-20 14:25:34
【问题描述】:

我有这个

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

当我尝试使用像

这样的参数时
[AcceptVerbs("POST")]
public JsonResult ShowProductsPerPage(string pageNumber)
{ ...

它不工作

但是当我使用

[AcceptVerbs("POST")]
public JsonResult ShowProductsPerPage(string id)
{ ...

一切正常。

这里是JS

    var currentUrl = window.location.protocol + '//' + window.location.host;
    var url = currentUrl + "/Products/ShowProductsPerPage/" + pageNumber;
    $.ajax({
        type: "POST",
        url: url,
        data: "",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            alert(data.pageNumber);
        }
    });

我在 JavaScript 中使用变量 pageNumber,所以我想保留相同的名称 方法背后的代码。

有可能吗?

【问题讨论】:

  • 只需将路由中的 {id} 更改为 {pageNumber}。
  • 向我们展示您如何将数据发布到控制器
  • @Dennisch 但是当我使用id 时,其他方法呢?他们不会工作。
  • 嗯,你不应该有两条参数完全相同的路由,只是名称不同。您可以在查询字符串中添加 pageNumber,并将其作为可选参数添加到路由中。
  • @Dennisch 是的,我知道。我想更改主要参数,它不可能像id always...

标签: c# javascript ajax asp.net-mvc asp.net-mvc-routing


【解决方案1】:

你有三个选择:

  • 第一个是(正如 cmets 所说),将现有路线中的 {id} 更改为 {pageNumber}

  • 第二个是创建一个新路由,它在某些方面有所不同,采用{pageNumber}。将此路线放在现有路线之前:

.

routes.MapRoute(
    name: "PageNumber",
    url: "Products/ShowProductsPerPage/{pageNumber}",
    defaults: new { controller = "Products", action = "ShowProductsPerPage" }
 );
  • 第三种方式是显式传递pageNumber作为参数:/Products/ShowProductsPerPage?pageNumber=5

【讨论】:

  • 谢谢!我刚刚检查了#2,这就是我需要的。
  • 它们都可以,最好的方法取决于具体情况。很高兴您找到了适合您的。
【解决方案2】:

只需将路由中的 {id} 更改为 {pageNumber}(以及相应的 url 参数)。参数应该有什么名称没有规定,id只是一个经常使用的名称。

【讨论】:

    【解决方案3】:

    将您的呼叫更改为:

    var url = currentUrl + "/Products/ShowProductsPerPage?pageNumber=" + pageNumber;
    

    【讨论】:

      猜你喜欢
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-15
      • 2018-04-27
      • 1970-01-01
      • 2016-03-22
      • 1970-01-01
      相关资源
      最近更新 更多