2
votes

I am using Html.ActionLink to generate a link.

@Html.ActionLink(item.Text, item.Author.UniqueName, "Author", new { selectedQuoteId = item.QuoteID }, null)

However when I use this method, the generated link is :

http://localhost/Author/aeschylus?selectedQuoteId=1627

But I would like it to be:

http://localhost/Author/aeschylus/1627

My configuration is:

routes.MapRoute( "AuthorQuotes", "Author/{authorUniqueName}/{selectedQuoteId}", new { controller = "AuthorQuotes", action = "Index", authorUniqueName = UrlParameter.Optional, selectedQuoteId = UrlParameter.Optional });

Is this possible to do this with Html.ActionLink ?

1

1 Answers

3
votes

Make sure that you have placed this custom route before the default one. Also you seem to have forgotten to provide a value for the authorUniqueName portion of your route. Since this is not the last part of your route pattern, it cannot be optional.

So start by fixing your route definition:

routes.MapRoute(
    "AuthorQuotes", 
    "Author/{authorUniqueName}/{selectedQuoteId}", 
    new { 
        controller = "AuthorQuotes", 
        action = "Index", 
        selectedQuoteId = UrlParameter.Optional 
    }
);

and then provide a value for this required parameter:

@Html.ActionLink(
    item.Text, 
    item.Author.UniqueName, 
    "Author", 
    new { 
        authorUniqueName = item.Author.UniqueName,
        selectedQuoteId = item.QuoteID 
    }, 
    null
)

Basically if you want to have optional parameters in a route, this can only be the last one. If you need to have multiple optional parameters then use query strings (just as you had), otherwise the routing engine cannot disambiguate between them.