开发者

Incorrect url generated by URL.Action and Html.ActionLink

开发者 https://www.devze.com 2023-04-07 22:26 出处:网络
I have routes: routes.MapRoute( \"NewsRoute\", \"News/{newsId}/{newsTitle}\", new { controller = \"News\",

I have routes:

routes.MapRoute(
    "NewsRoute",
    "News/{newsId}/{newsTitle}",
    new {
        controller = "News",
        action = "News",
        newsId = UrlParameter.Optional,
        newsTitle = UrlParameter.Optional
    }
);
routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Home", id = UrlParameter.Optional } // Parameter defaults
);

and usage:

@Url.Action("News", "News", new { newsId = "", newsTitle = "" })

开发者_高级运维I want to have "/News" url, but instead "/News/News" is being generated. Default route is used I guess. So the question is why NewsRoute is skipped?


The solution was to split route with 2 optional parameters and action to two separate actions:

routes.MapRoute(
    "NewsRoute",
    "News", new {
        controller = "News",
        action = "Index"
    }
);

routes.MapRoute(
    "Specific News",
    "News/{id}/{title}",
    new {
        controller = "News",
        action = "News",
        title = UrlParameter.Optional
    }
);
0

精彩评论

暂无评论...
验证码 换一张
取 消