Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RouteValueDictionary ignores empty values

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?

like image 373
UserControl Avatar asked Apr 12 '26 07:04

UserControl


1 Answers

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.

like image 189
NightOwl888 Avatar answered Apr 13 '26 22:04

NightOwl888



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!