Search code examples
asp.net-mvcasp.net-mvc-routingactionlink

ASP.NET MVC Actionlink returns empty link


I'm having this issue and have searched Google and StackOverflow, but it seems I can't find a solution for it.

I'm having the following routes mapped in Global.asax.cs

 routes.MapRoute(
       "posRoute", // Route name
       "pos/{guid}", // URL with parameters
       new { controller = "Pos", action = "Index", guid = UrlParameter.Optional } // Parameter defaults
 );

 routes.MapRoute(
       "foxRoute", // Route name
       "fox/{guid}", // URL with parameters
       new { controller = "Fox", action = "Index", guid = UrlParameter.Optional } // Parameter defaults
        );

I want to make a link with the HTML helper Actionlink but it keeps returning an empty link.

@Html.ActionLink("Proceed", "device")

returns

<a href="">Proceed</a>


@Html.ActionLink("Proceed", "device", "Fox" , new { guid = "test" })

returns

<a href="" guid="test">Proceed</a>

as the expected result is as follow:

<a href="/fox/index/test">Proceed</a>

or better

<a href="/fox/test">Proceed</a>

Solution

  • try this overload.

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

    so your code will be

    @Html.ActionLink("Proceed", "device", "Fox" , new { guid = "test" },null)
    

    If you want to pass any HTML attributes like CSS class/ ID of element, you can replace the last parameter calue (null in our case) with that.

    Also make sure that you have the generic route definition below your specific routes

    routes.MapRoute(
                "posRoute", 
                "pos/{guid}", 
                new { controller = "Pos", action = "Index", 
                guid = UrlParameter.Optional } // Parameter defaults
            );
    
    routes.MapRoute(
                "foxRoute", // Route name
                "fox/{guid}", // URL with parameters
                new { controller = "Fox", action = "Index",
                guid = UrlParameter.Optional } // Parameter defaults
            );
    
    routes.MapRoute("Default","{controller}/{action}/{id}",
              new { controller = "Home", action = "Index",
                        id = UrlParameter.Optional })