Search code examples
c#asp.net-core.net-coreasp.net-core-2.0asp.net-core-tag-helpers

How Do I Pass an Array of Values via Anchor Tag Helper?


I'm using Asp.Net Core 2.1 Pages

public async Task OnGetAsync([FromQuery(Name = "status")] string[] myValues)
{

}

I'm trying to pass in an array of values from an anchor tag helper, but all I receive in myValues is one item. If I manually type out the query string to mirror MyRoute?myValues=A&myValues=B, it works as expected. I've tried the following with no success.

<a asp-page="/MyPage" asp-route-status="A" asp-route-status="B">Click</a>

<a asp-page="/MyPage" asp-route-status="new [] { A, B }">Click</a>

<a asp-page="/MyPage" asp-route-status="@(new [] { A, B })">Click</a>

@{  var list = new string[] { "A", "B" };}
<a asp-page="/MyPage" asp-route-status="@list">Click</a>

Solution

  • This doesn't appear to be possible - The value passed in to asp-route-status is expected to either be a string or a value that it is then converted to a string anyway. You can see this in the source code, where the RouteValues property is a dictionary of <string, string>.

    Let's look at your first example, which looks like this:

    <a asp-page="/MyPage" asp-route-status="A" asp-route-status="B">Click</a>
    

    I'm using Visual Studio with all its intellisense magic - when I use this code snippet, I am warned via a green squiggly and tooltip that the "Attribute 'asp-route-status' already exists.". The end result here is that only the first value specified is actually passed into the query-string.

    With either of your valid array approaches, the generated value for status is simply a ToString of the array - System.String%5B%5D.

    It appears that in order to achieve what you want, you're going to need to fallback to the traditional UrlHelper approach. Here's what that looks like:

    <a href="@Url.Page("/MyPage", new { status = new [] { "A", "B" } })">Click</a>
    

    I found this Github issue where the most recent comment (2017-11-24) asks about how to achieve this with a tag-helper, but the question has not been answered as of today (2018-08-10).