Routing ASP.NET MVC URL to url with querystring

2019-07-18 10:31发布

I have to map a nice looking ASP.NET MVC URL '/sel/F/61' to an ASPX url with query string parameters like 'familydrilldown.aspx?familyid=61'. I tried to add this to global.asax:

routeTable.MapPageRoute(
                "selectorroute", 
                "sel/F/{familyid}", 
                "~/selector/familydrilldown.aspx");

which works, except that the familyid is not passed as a querystring to familydrilldown.aspx.

How can I take the {familyid} and pass it as a querystring parameter to the page familydrilldown.aspx?

I tried this:

routeTable.MapPageRoute(
                "selectorroute", 
                "sel/F/{familyid}", 
                "~/selector/familydrilldown.aspx?familyid={familyid}");

but of course this doesn't really work...

Any ideas on how to do this?

Thanks!

2条回答
Fickle 薄情
2楼-- · 2019-07-18 11:08

I don't know if what you want is possible. Why don't you just use?

var familyId = Page.RouteData.Values["familyid"]

in the Page_Load (there might be some casting involved)

查看更多
淡お忘
3楼-- · 2019-07-18 11:10

I found a solution by implementing my own IRouteHandler:

public class SelectorRouteHandler<T> : IRouteHandler 
    where T : IHttpHandler, new()
{                                      
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        string queryString = 
            "?familyid=" + requestContext.RouteData.Values["familyid"];

        HttpContext.Current.RewritePath(
            string.Concat("~/selector/familydrilldown.aspx", queryString));

        var page = BuildManager.CreateInstanceFromVirtualPath(
            "~/selector/familydrilldown.aspx", typeof(T)) as IHttpHandler;

        return page;                    
    }
}

and registering it like:

routeTable.Add(
    "selectorRoute", 
    new Route("sel/F/{familyid}", SelectorRouteHandler<Page>()));
查看更多
登录 后发表回答