c# - 如何为路由实现另一个 var 参数名称

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

我有这个

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}在您现有的 route 。

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

.

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

关于c# - 如何为路由实现另一个 var 参数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18337570/

相关文章:

javascript - Symfony|Twig : update data after ajax call

c# - 正则表达式分隔两个括号封闭项目

c# - 为什么不能在类级别使用 'NonSerialized' 属性?如何防止类的序列化?

c# - 在表达式树中使用属性表达式的值

javascript - innerHTML 不会覆盖

javascript - 如何在 Javascript 中显示特定格式的日期?

php - 如何在一个页面上运行多个ajax调用

c# - 如何清除表单中所有textBoxes的文字?

javascript - 如何在径向进度条上显示部分?

javascript - 无溢出的可滚动 div :auto?