Friday, February 14, 2014

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 )

        [HttpGet]
        [GET("users/manage/{id:int?}")]
        [Authorize]
        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">
   <li>
      <a href="@Url.Action("Manage", "Account", new { id = "" })">Manage Users</a>
   </li>
   <li>
      <a href="@Url.Action("CreateAccount", "Account")"></a>   
   </li>
</ul>