1

Just one easy question about default parameter values in the routing.

If I have a route in global asax with the following data:

Name: "DetailPage"
Pattern:/{companytitle}/{departmenttitle}/{persontitle}
Controller="Person"
Action="Detail"

And I'm using the following helper in my views:

@(Url.RouteUrl("DetailPage",new{companytitle=Model.Companytitle, departmenttitle=Model.DepartmentTitle,persontitle=Model.PersonTitle}))

Lets imaging that property of the model DepartmentTitle is null, how I could set a default value in the Route?

2 Answers 2

3

Just define them as part of the route and give them default values like below:

routes.MapRoute("DetailPage",
                "/{companytitle}/{departmenttitle}/{persontitle}",
                new { controller = "Person", action = "Detail", departmenttitle = "Science", persontitle ="Me" }
                );
Sign up to request clarification or add additional context in comments.

4 Comments

And if you send the following request /somecompany/foo what will be passed as arguments to the Detail action (assuming this action takes 3 arguments corresponding to the 3 route parameters)?
companytitle = somecompany, departmenttitle = foo, persontitle = Me
@amurra, yes, but I don't want this. I want companytitle = somecompany, departmenttitle = Science, persontitle = foo as per the OP's requirement. He wants to define a default value for the departmenttitle parameter assuming it is not part of the request which obviously is not possible as the routing engine is not able to disambiguate the parameters in this case. That's why only the last parameter in a route definition can be null.
@Darin - I agree with you and your example makes sense. I was just showing how to set a default value for a parameter if not specified. This will only work if both the persontitle and departmenttitle are left out of the route, otherwise the situation you stated will happen and then their routes need to be rethought and reworked.
2

Lets imaging that property of the model DepartmentTitle is null

You shouldn't imagine such thing. Only the last parameter in a route can be null (or empty). If a parameter can be null (or empty) it should not be part of your route definition (unless of course this is the last parameter of this route definition) but passed as query string.

In your case simply define the route like this:

{companytitle}/{persontitle}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.