Search code examples
asp.net-mvcrazorviewbaghtml.actionlink

Html.ActionLink with ViewBag


I currently have a ActionLink in Razor that looks like this:

@Html.ActionLink("Back to News", "Index")

However, I wish to add a ViewBag to it

@ViewBag.groupid

Thus the rendering of the ActionLink to know to instead of being simply:

<a href="/">Back to News</a>

To instead have changed the URL to be Index/@ViewBag.groupid ( Index/5 )

so that URL is then

/Index/5   ( where 5 is the ViewBag.groupid)   

Solution

  • There's an overload (a few actually) that take routeValues. Set routeValues to a new anonymous object with an id property set to ViewBag.groupid.

    @Html.ActionLink("Back to News", "Index", "controller name", 
                     new {id = ViewBag.groupid}, null)