Sunday, 9 March 2014

How to hide querystring parameter name from an URL generated with Html.ActionLink in ASP.NET MVC

 In View we are going to create link using Html helper :
@Html.ActionLink("Address", "ViewAddress", new { addressId = Guid.NewGuid() })
that will give us :

http://localhost:100/Home/ViewAddress?addressId=5f89a656-e98c-4680-b98f-6a3cf4ede7aa

We want to hide query string addressId and have only :

 http://localhost:100/Home/ViewAddress/5f89a656-e98c-4680-b98f-6a3cf4ede7aa

The solution is to add new map route.

Open RouteConfig.cs file from App_Start folder and add new Map Route:

routes.MapRoute("ListingPreview", "Home/ViewAddress/{addressId}",
                new
                {
                    controller = "Home",
                    action = "ViewAddress",
                    addressId= UrlParameter.Optional
                }
                );