In ASP.NET MVC, how to generate duplicate names ('? V = 1 and v = 2 and v = 3') of a query string using Html.ActionLink

This is not a question of how to correctly attach a series of flags to a model property (general question) - my site works fine with reading the values ​​of a flag from a request, or a POST request line, or GET +.

This is about how to use it Html.ActionLinkto create a link that correctly generates several checkbox values ​​in the query string.

So, I have the following model:

public class ModelType
{
    public string[] V { get; set; }
}

And I bind, say, 3 flags to this model in the view, since I have three possible values ​​(and, yes, combinations of the specified values).

Here is the final HTML

<INPUT id="chk1" value="1" type="checkbox" name="V">
<INPUT id="chk2" value="2" type="checkbox" name="V">
<INPUT id="chk3" value="3" type="checkbox" name="V">

, GET, , , ?V=1&V=2&V=3.

, .

, , , RouteValueDictionary ; , - :

1: ModelType :

<%= Html.ActionLink("Test link", null /* action name */, new { V = Model.V }) %>

2: 'V' :

<%= Html.ActionLink("Test link", null /* action name */,
    new { V = new string[] { "1", "2", "3" } }) %>

[ RouteValueDictionary, .]

: ?V=System.String%5B%5D.

, , ToString() ; , , MVC , ?V=1&V=2&V=3.

:

new { V="1", V="2", ... }

Nor RouteValueDictionary :

d["V"] = "1"; d["V"] = "2"; ...

RouteValueDictionary, IEnumerable<string> , , - : ?V=1%2C2%2C3.

, , MVC ​​ ( ); , , , , .

, .

- ? ActionLink, , ?

, , .

+3
2

, , . , - , - .

Html.ActionLink , URL-, , () (!) System.Web.Mvc.ParsedRoute, Bind System.Web.Routing.

( Reflector) - :

if (unusedNewValues.Count > 0)
{
    bool flag5 = true;
    foreach (string str2 in unusedNewValues)
    {
        object obj5;
        if (acceptedValues.TryGetValue(str2, out obj5))
        {
            builder.Append(flag5 ? '?' : '&');
            flag5 = false;
            builder.Append(Uri.EscapeDataString(str2));
            builder.Append('=');
            builder.Append(Uri.EscapeDataString(
              Convert.ToString(obj5, CultureInfo.InvariantCulture)));
        }
    }
}

, unusedNewValues - HashSet<string>, , , - /.

a=b&a=c(...), - , Mvc , .

, - ( ):

public class StringCollection : List<string>
{
  public override string ToString()
  {
    //use the pipe character as a delimiter - but this doesn't work
    //if the strings being carried around ccould naturally contain '|'!
    return string.Join("|", this.ToArray());
  }
}

( DefaultModelBinder) , , , , '|' . , , .

, , .

, , ...

+3

. , HtmlHelper/RouteValueDictionary URL . - :

<a href="/Controller/Action?<%: string.Join("&", set.Select(i => "v=" + i))%>">Link</a>

, .

+1

Source: https://habr.com/ru/post/1780438/


All Articles