Fix for @Url.Action() Returns With Optional Parameters

I was working on this super cool admin panel using MVC4 and I wanted my sidebar links to work perfectly on my actions.

The problem was that I had an Controller action with a optional parameter (id) and every time the page gets rendered, if there is an id in the url of the current page, the whole thing gets plugged into this Url.Action() return value.

This is my action. ( I am using AttributeRouting )

        public ActionResult Manage(int? id)

            return id.HasValue ?  
               View("CreateAccount", new CreateAccountModel() { ID = id }) 
             : View();

After searching for an answer, It is because, Url.Action uses context information to render url

A little bit of markup with correct implementation will look like this.

<ul class="collapse" id="menu-users">
      <a href="@Url.Action("Manage", "Account", new { id = "" })">Manage Users</a>
      <a href="@Url.Action("CreateAccount", "Account")"></a>   

Popular posts from this blog

Print a receipt using a Thermal Printer with C#.NET

Automatic redirect upon session timeout using ASP.NET MVC and Javascript

Complex Master-Detail Form using Knockout.js and ASP.NET MVC