Search code examples
actionlinkasp.net-mvc-5

ActionLink with parameter in another controller MVC5


Can i create an action link to another controller and the action method takes a parameter?

the ordinary action link is:

@Html.ActionLink("Home", "Index", "Table1")

and if we have an actionlink to an action method inside the controller:

@Html.ActionLink("Edit", "Edit", new { id=item.ID })

Now what if i want to go to an action link to an action method inside another controller? What it will look like?

i.e. There is an action method Action1 that takes a parameter ParentID in the contoller Table2 How can i write an action link to this action method?


Solution

  • There is another overload of ActionLink helper which lets you specify the controller name, action name and the route values.

    public static MvcHtmlString ActionLink(
        this HtmlHelper htmlHelper,
        string linkText,
        string actionName,
        string controllerName,
        object routeValues,
        object htmlAttributes
    )
    

    So if you want to render a which points to Table2/Action1, you ca use that overload

    @Html.ActionLink("Edit", "Action1","Table2", new { ParentID = 100 },null)
    

    You can change hardcoded 100 with your actual value.