5

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?

JoeBrockhaus
  • 2,745
  • 2
  • 40
  • 64

1 Answers1

5

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" });
haim770
  • 48,394
  • 7
  • 105
  • 133
  • I haven't tried this and I already changed the code to create the link manually, but I'm going to accept this since you seem to know exactly how to fix it and you were lightning fast! :D – JoeBrockhaus Jul 17 '13 at 15:19
  • 1
    I did try it and it does seem to generate `item1=&item2=value`. Thanks. – haim770 Jul 17 '13 at 15:21
  • 2
    Since the `ToString()` implementation for DBNull is defined to return `String.Empty` you can alternatively use `DBNull.Value` and avoid the need to define the `EmptyParameter` class. – Christopher King Jan 27 '17 at 19:09
  • Why the heck the .Net team removes empty values inside `RouteCollection.GetVirtualPathForArea(HttpContext,string)`? What's the reason? Anyway thanx, excellent solution! i was losing an entire day behind this. – T-moty Jan 30 '20 at 16:52
  • @ChristopherKing better use `UrlParameter.Optional` since is more related than `DBNull.Value` and is less confusing – T-moty Jan 30 '20 at 16:59