【问题标题】:QueryString Parameters in Mvc strongly typed actionlinksMvc 强类型操作链接中的 QueryString 参数
【发布时间】:2010-11-08 23:08:30
【问题描述】:

我认为在通过强类型操作链接创建操作链接时,除了操作参数列表之外,没有可用于添加参数的重载。我想要的是添加额外的参数,这些参数将在 querystring 中可用。
例如,控制器 MyController 中的操作 MyAction(int id)Html.ActionLink(mc=>mc.MyAction(5),"My Action") 会产生类似 MyController/MyAction/5 的链接,但我想要的是追加查询字符串像这样。 MyController/MyAction/5?QS=Value。有没有办法,使用强类型的动作链接,来实现这一点。

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:
    <%=Html.ActionLink(LinkName, Action, Controller, new { param1 = value1, param2 = value2 }, new { })%>
    

    【讨论】:

    • 我正在这样做:@Html.ActionLink(" ", "Create" & "?parID=Automatic&parController=" & ViewData("Action").ToString, "Controller", New With {. area = "MyArea"}, New With {.class= "imgNew"}),这在 MVC2 中工作,但是当我尝试在 MVC3 上做同样的事情时,我得到这个错误:一个潜在危险的 Request.Path 值是从客户端检测到。显然参数是问题所以我更正:@Html.ActionLink(" ", "Create", "Controller", New With {.area = "MyArea", .parID = "Automatic", .parController = ViewData(" Action").ToString},新的 {.class= "imgNew"})。
    【解决方案2】:

    为此创建自定义助手。试试这样的:

    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);
    }
    

    【讨论】:

      【解决方案3】:

      您不需要创建扩展方法,只需更改您的路由配置:

        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
             );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-09-17
        • 2013-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多