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

孤者浪人 提交于 2021-01-27 21:22:53

问题


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?


回答1:


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
    }
}



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/5231198/how-do-i-get-rid-of-the-question-mark-in-an-asp-net-mvc-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!