RouteValueDictionary ignores empty values

耗尽温柔 提交于 2019-12-08 02:14:43

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/22009162/routevaluedictionary-ignores-empty-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!