2

I have few empty route values I want in the query string:

var routeValues = new RouteValueDictionary();
routeValues.Add("one", "");
routeValues.Add("two", null);
routeValues.Add("three", string.Empty);

If I then pass it to UrlHelper.RouteUrl() it ignores all the values and the generated query string is empty. However, urls like /?one=&two=&three= are perfectly valid. How can I do that?

UserControl
  • 14,766
  • 20
  • 100
  • 187

1 Answers1

4

This behavior is built into the default Route class. It calls into the ParsedRoute.Bind() method where it does this check:

if (IsRoutePartNonEmpty(obj2))
{
    acceptedValues.Add(key, obj2);
}

Which does this:

private static bool IsRoutePartNonEmpty(object routePart)
{
    string str = routePart as string;
    if (str != null)
    {
        return (str.Length > 0);
    }
    return (routePart != null);
}

This effectively prevents any query string values from being output if they are empty. Everything it does is private, static, internal, and otherwise impossible to override. So, there are really only 2 options to override this behavior.

  1. Subclass Route and override GetVirtualPath(), replacing ParsedRoute.Bind() with a custom implementation.
  2. Subclass RouteBase and create a custom route implementation.

I guess the 3rd option is to leave it alone, as others have pointed out this isn't really a problem since having an empty parameter in the query string has little or no value.

NightOwl888
  • 55,572
  • 24
  • 139
  • 212
  • String is fine. but it ignores Guid.Empty (00000000-0000-0000-0000-000000000000) too. Unfortunately you cannot use Guid.Empty as a default action parameter as it is not a compile-time constant. – Kev Nov 21 '16 at 11:36
  • 1
    Having missing empty parameters is a huge problem if your url needs to be hashed for validation. – anber Jun 06 '19 at 03:18