使用asp.net MVC和RouteUrl创建URL

时间:2022-11-30 21:27:17

I would like to get the current URL and append an additional parameter to the url (for example ?id=1)

我想获取当前的URL并在url中附加一个额外的参数(例如?id = 1)

I have defined a route:

我已经定义了一条路线:

        routes.MapRoute(
            "GigDayListings",                                   // Route name
            "gig/list/{year}/{month}/{day}",                    // URL with parameters
            new { controller = "Gig", action = "List" }         // Parameter defaults
        );

        In my view I have a helper that executes the following code: 

        // Add page index
        _helper.ViewContext.RouteData.Values["id"] = 1;

        // Return link
        var urlHelper = new UrlHelper(_helper.ViewContext);
        return urlHelper.RouteUrl( _helper.ViewContext.RouteData.Values);

However this doesnt work.

然而,这不起作用。

If my original URL was : gig/list/2008/11/01

如果我的原始网址是:gig / list / 2008/11/01

I get

gig/list/?year=2008&month=11&day=01&id=1

I would like the url to be: controller/action/2008/11/01?id=1

我想网址是:controller / action / 2008/11/01?id = 1

What am I doing wrong?

我究竟做错了什么?

1 个解决方案

#1


1  

The order of the rules makes sence. Try to insert this rule as first.

规则的顺序是有效的。尝试首先插入此规则。

Also dont forget to define constraints if needed - it will results in better rule matching:

如果需要,也不要忘记定义约束 - 它将导致更好的规则匹配:

routes.MapRoute(
    "GigDayListings",                                // Route name
    "gig/list/{year}/{month}/{day}",                // URL with parameters
    new { controller = "Gig", action = "List" },    // Parameter defaults
    new
        {
            year = @"^[0-9]+$",
            month = @"^[0-9]+$",
            day = @"^[0-9]+$"
        }    // Constraints
);

#1


1  

The order of the rules makes sence. Try to insert this rule as first.

规则的顺序是有效的。尝试首先插入此规则。

Also dont forget to define constraints if needed - it will results in better rule matching:

如果需要,也不要忘记定义约束 - 它将导致更好的规则匹配:

routes.MapRoute(
    "GigDayListings",                                // Route name
    "gig/list/{year}/{month}/{day}",                // URL with parameters
    new { controller = "Gig", action = "List" },    // Parameter defaults
    new
        {
            year = @"^[0-9]+$",
            month = @"^[0-9]+$",
            day = @"^[0-9]+$"
        }    // Constraints
);