Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.Actionlink with ID

I have this code:

@Html.ActionLink("Back To Blog","Blog","Home", new {Model.BlogId}, null)

That code is generating this HTML:

<a href="/Home/Blog?BlogId=1">Back To Blog</a>

But what I want it to generate is this:

<a href="/Home/Blog/1">Back To Blog</a>

How do I fix this?

PS - I saw this post on SO which seems to indicate I'm doing it the right way, but I am not getting the results I want. I am using MVC4, latest version.

like image 848
Todd Davis Avatar asked Apr 10 '13 02:04

Todd Davis


1 Answers

I suspect you don't have a route configured for Home/Blog/{BlogId}. So if you want to be able to write this (as what you show in your code):

@Html.ActionLink("Back To Blog","Blog","Home", new { Model.BlogId}, null)

You need to have a route like this:

routes.MapRoute(
    name: "DefaultBlog",
    url: "{controller}/{action}/{blogid}",
    defaults: new { controller = "Home", action = "Blog", 
            blogid = UrlParameter.Optional }
);

Notice the third part of the url which is named blogid. But if you don't want to configure another route then you can just rewrite your link as:

@Html.ActionLink("Back To Blog","Blog","Home", new { id = Model.BlogId}, null)

Notice the id on the parameter.

like image 83
von v. Avatar answered Sep 23 '22 18:09

von v.