简体   繁体   中英

How do I get rid of the question mark in an ASP.NET MVC route?

I have the following route defined:

{theme}/{subtheme}/{contenttype}/{contentdetail}/Print

When I use
Url.Action ("PrintLayout","Page",new {contentUrlTitle = Model.ContentUrlTitle}

I get the following link:

/theme1/subtheme1/contenttype1/myfirstcontenturltitle?action=PrintLayout 

I'd like for it to be a RESTful URL.

/theme1/subtheme1/contenttype1/myfirstcontenturltitle/Print

Do you know what im missing here?

Since you haven't posted your routes Table (hint: Post your routes table), I'll have to guess as to what the route is. If you want this to work, the route needs to be:

routes.MapRoute("contentDetail",
    "{theme}/{subtheme}/{contenttype}/{contentdetail}/print"
    new { controller = "Page", action = "PrintLayout", theme="", subtheme="", contenttype = ""     
    });

Then your controller:

public class PageController
{
    public ActionResult PrintLayout(string theme, string subtheme, string contenttype, string contentdetail)
    {
        //do print stuff here
    }
}

Jose3d,

  1. One important thing to note is that 'controller' and 'action' parameters are treated as special parameters in ASP.NET MVC. These parameters are supplied for url matching even though they may not explicitly be specified in the parameter values section.

Therefore, the below statement:

Url.Action ("PrintLayout","Page",new {contentUrlTitle = Model.ContentUrlTitle}

will supply the following parameters for route matching:

controller = "Page", action = "PrintLayout", contentUrlTitle = "{value of Model.ContentUrlTitle}"

As you can see here, 'controller' and 'action' parameters are implicitly defined by ASP.NET MVC.

  1. Another thing that many developers don't understand about the ASP.NET MVC routing is that, during route matching, any parameters supplied in excess will appear in the url as "query strings"

Excess parameters are ones that don't appear in the url.

For your case, the 'action' parameter does not appear in the url therefore it will be treated as 'excess parameter' and that's is why it appears as a query string.

My suggestion is that: try to reformat your url so that {action} is part of the url segment.

One thing I don't understand is why 'controller' parameter does not also appear as a query string? Perhaps providing more detail could be more helpful.

I think you can try this:

Url.Action("PrintLayout/Print", "Page");

The thing is that when you use a Dictionary to parse a new parameter the default behaviour is that one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM