Search code examples
asp.net-mvcrazorparametersquery-stringactionlink

MVC Html.ActionLink removes empty querystring parameter from URL


I'm using the Html.ActionLink(string linkText, string actionName, object routeValues) overload to send some params to an Action Method..

Sometimes I need to pass an empty parameter value like: ?item1=&item2=value

I'm specifying the param in the anonymous type I create and pass as routeValues, but both null and string.Empty result in a URL that omits the empty item1 param.

new { item1 = null, item2 = "value" } 
new { item1 = string.Empty, item2 = "value" }
new { item1 = "", item2 = "value" }

// all result in:
?item2=value

I can create the URL manually but I want to use the helper method.

Suggestions?


Solution

  • Create an EmptyParameter class as follows:

    public class EmptyParameter
    {
        public override string ToString()
        {
            return String.Empty;
        }
    }
    

    Then:

    @Html.ActionLink("Action",
                     "Controller",
                      new { item1 = new EmptyParameter(), item2 = "value" });