2

I have seen this answer describing ASP.NET support for keyless (not valueless) parameters, like http://some.url?param1&param2, and confirmed them to be viewable on Request.QueryString like:

var values = this.Request.QueryString.GetValues(null);
values.Any(o => o == "param1");

This is fine and dandy but now I want to generate urls like this. My first intuition was to use the RouteValueDictionary: routeValues parameter of Url.Action with null as a key:

@{ 
    var dict = new RouteValueDictionary();
    dict.Add(null, "param1");
    dict.Add(null, "param2");
}
<a href="@Url.Action("ActionName", dict)">Very link, amaze</a>

But apparently C# forbids nulls as dictionary keys because of reasons.

I have also tried the empty string as the key, but it results in a query string like: ?=param1,=param2 which contains 2 more equal signs that I want it to.

Of course I can string manipulate the heck out of my URL and add the &param1 part to the query string, but I was hoping for a concise solution.

Community
  • 1
  • 1
vinczemarton
  • 7,756
  • 6
  • 54
  • 86

2 Answers2

1

You want to add the key values, but leaving the value null isn't allowed.

RouteValueDictionary ignores empty values

You could add a value like 1 for instance, but you lose your fine and dandy solution.

    @{
        var dict = new RouteValueDictionary();
        dict.Add("param1",1);
    }
    <a href="@Url.Action("Index", dict)">Very link, amaze</a>

For another solution you will have to write some custom code.

Community
  • 1
  • 1
Ruben-J
  • 2,663
  • 15
  • 33
  • Could you clarify? If you specify `"param1"` key and null or string.Empty value the Url.Action helper will not include this parameter in the generated url. Or maybe I misunderstood what you mean? – Darin Dimitrov Jan 09 '17 at 14:34
  • I thought it would work but i edited my answer cause empty values are indeed ignored. – Ruben-J Jan 09 '17 at 14:39
  • 1
    Sadly including placeholder values like 1 is precisely what I don't want to do, that is precisely why I asked the question. – vinczemarton Jan 09 '17 at 14:44
0

Since there's no built-in helper for this why don't you roll your own:

public static class UrlHelperExtensions
{
    public static string MyAction(this UrlHelper urlHelper, string actionName, IList<string> parameters)
    {
        string url = urlHelper.Action(actionName);
        if (parameters == null || !parameters.Any())
        {
            return url;
        }

        return string.Format("{0}?{1}", url, string.Join("&", parameters));
    }
}

and then:

@{
    var parameters = new List<string>();
    parameters.Add("param1");
    parameters.Add("param2");
}

@Url.MyAction("ActionName", parameters)
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928