QueryString options in Mvc strongly typed actionlinks

I think there is no overload available to add parameters other than the action parameter list when creating an actionlink through strongly typed action links. I want to add additional parameters that will be available in querystring.
For example, with the action MyAction (int id) in the controller MyController . Html.ActionLink (mc => mc.MyAction (5), "My Action") will produce something like MyController / MyAction / 5 , but I want to add a querystring append like this. MyController / MyAction / 5? QS = Value . Is there a way using strictly typed actionlinks to achieve this.

+3
source share
3 answers
<%=Html.ActionLink(LinkName, Action, Controller, new { param1 = value1, param2 = value2 }, new { })%>
+4
source

Create a special assistant for this. Try something like this:

public static string MyActionLinkWithQuery<TController>(this HtmlHelper helper, Expression<Action<TController>> action, string linkText,
    RouteValueDictionary query) where TController : Controller
{
    RouteValueDictionary routingValues = ExpressionHelper.GetRouteValuesFromExpression(action);

    foreach(KeyValuePair<string, object> kvp in query)
        routingValues.Add(kvp.Key, kvp.Value);

    return helper.RouteLink(linkText, routingValues, null);
}
+1
source

You do not need to create extension methods, just change the routing configuration:

  routes.MapRoute(null,
       "MyController/MyAction/{id}",
        new { controller = "MyController", action = "MyAction", id="" } // Defaults
       );


        routes.MapRoute(
       null
      , // Name
       "{controller}/{action}", // URL
       new { controller = "MyController", action = "MyAction" } // Defaults
       );
0
source

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


All Articles