How to pass routeValues ​​containing hyphen through actionlink in asp.net mvc 5

I have an actionlink, I need to pass a parameter containing a hyphen (-). Changing the naming convention is not possible. How to do it?

<li>@Html.ActionLink("abc", "abc", "abc", new { area = "",sap-ie="Edge" }, new { id = nav_abc"})</li> 

This gives me the error "Invalid Anonymous Type Declarator" because it contains a hyphen. Basically I need an actionlink to generate html, as shown below.

 <a href=".../abc?sap-ie=Edge" id="nav_abc" >abc</a> 
+6
source share
3 answers

If you are sure that the URL will not change significantly from the structure you specify, you can use the anchor tag and build the URL from Url.Action .

 <a href='@Url.Action("abc", "abc")?sap-ie=Edge'>abc</a> 

The whole point of htmlhelpers is to help generate html anyway .. so if it bothers you, you can go down to the html itself and just do it.

+3
source

I just wanted to point out that this is not that the underscore trick only works with data attributes, it only works with passing HTML attributes in general. This is because it makes sense to change the underscores to hyphens in the HTML context, since underscores are not used in HTML attributes. However, it is perfectly fair for you to have an underlined route parameter, so the structure cannot make any assumptions about your intentions.

If you need to pass route values ​​with a hyphen, you should use RouteValueDictionary . This is simply a limitation of anonymous objects that cannot be overcome.

 <li>@Html.ActionLink("abc", "abc", "abc", new RouteValueDictionary { { "area", "" }, "sap-ie", "Edge" } }, new RouteValueDictionary { { "id", "nav_abc" } })</li> 

Unfortunately, there is no ActionLink overload that accepts both RouteValueDictionary for routeValues and an anonymous object for htmlAttributes , so including one means switching both. You can technically use any implementation of IDictionary for the htmlAttributes parameter, so you can only use new Dictionary { { "id", "nav_abc" } } . It depends on you.

+2
source

Have you tried to use this overload of the ActionLink method?

  @{ var routeValues = new RouteValueDictionary(); routeValues.Add("sap-ie", "Edge"); routeValues.Add("area", ""); var attributes = new Dictionary<string, object>(); attributes.Add("Id", "nav_abc"); } @Html.ActionLink("Go to contact page", "Contact", routeValues, attributes) 
+1
source

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


All Articles