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?

1 Answer 1

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" });
Sign up to request clarification or add additional context in comments.

5 Comments

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
I did try it and it does seem to generate item1=&item2=value. Thanks.
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.
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.
@ChristopherKing better use UrlParameter.Optional since is more related than DBNull.Value and is less confusing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.