MVC Html.ActionLink从URL中删除空的查询字符串参数

5
我使用Html.ActionLink(string linkText, string actionName, object routeValues)重载来向Action方法传递一些参数。
有时我需要传递一个空的参数值,例如:?item1=&item2=value 我在创建的匿名类型中指定参数,并将其作为routeValues传递,但是nullstring.Empty都会导致URL省略空的item1参数。
new { item1 = null, item2 = "value" } 
new { item1 = string.Empty, item2 = "value" }
new { item1 = "", item2 = "value" }

// all result in:
?item2=value

我可以手动创建URL,但我想使用helper方法。
有什么建议吗?
1个回答

5
创建一个名为EmptyParameter的类,内容如下:
public class EmptyParameter
{
    public override string ToString()
    {
        return String.Empty;
    }
}

然后:

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

我还没有尝试过这个,但我已经改变了代码以手动创建链接,但是我会接受这个建议,因为你似乎知道如何完美解决它,并且你的速度非常快! :D - JoeBrockhaus
1
我尝试了一下,它似乎生成了item1=&item2=value。谢谢。 - haim770
2
由于DBNull的ToString()实现被定义为返回String.Empty,因此您可以选择使用DBNull.Value,从而避免定义EmptyParameter类的需要。 - Christopher King
.Net团队为什么要在RouteCollection.GetVirtualPathForArea(HttpContext,string)中删除空值?这是什么原因呢?无论如何,感谢你提供的绝佳解决方案!我已经花了整整一天的时间来解决这个问题。 - T-moty
@ChristopherKing 最好使用 UrlParameter.Optional,因为它比 DBNull.Value 更相关,更不容易混淆。 - T-moty

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接