2

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Another problem was that I was using "item.Author.UniqueName" instead of "index" as action. And "Author" instead of "AuthorQuotes" as controller. So I think the routing engine was just skipping my route and going straight to the default route after.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.