2012-02-09 64 views
2

我使用Html.ActionLink()创建链接。我根据从URL获取的查询字符串的条件向url添加参数字符串。Html.ActionLink中的Concat字符串()

<% 
strA = Request.QueryString["AA"]; 
strB = Request.QueryString["BB"]; 
strC = Request.QueryString["CC"]; 

if (!string.IsNullOrEmpty(strA)) 
{ 
%> 
    <%: Html.ActionLink(a.Name, Model.ActionName, Model.ControllerName, 
     new {aa = strA , tab = 2}, null)%> 
<% 
}else if(!string.IsNullOrEmpty(strB)){ 
%> 
    <%: Html.ActionLink(a.Name, Model.ActionName, Model.ControllerName, 
     new {bb = strB , tab = 2}, null)%> 
<% 
}else if(!string.IsNullOrEmpty(strA) && !string.IsNullOrEmpty(strB)){ 
%> 
    <%: Html.ActionLink(a.Name, Model.ActionName, Model.ControllerName, 
     new {aa = strA , bb = strB, tab = 2}, null)%> 
<%else{ %> 
    <%: Html.ActionLink(a.Name, Model.ActionName, Model.ControllerName, 
     new {tab = 2}, null)%> 
<% }%> 

这就是我试图做的:

<% 
string url_add = ""; 
if (!string.IsNullOrEmpty(strA)) 
{ 
    url_add += "aa=strA"; 
}else if(!string.IsNullOrEmpty(strB)){ 
    url_add += "bb=strB"; 
}else if(!string.IsNullOrEmpty(strA) && !string.IsNullOrEmpty(strB)){ 
    url_add += "aa=strA&bb=strB"; 
}else{ 
    url_add += "tab=2"; 
} 
%> 

后,我Concat的字符串准备好了,我把下面那个字符串:

<%: Html.ActionLink("My link", "my_action", "my_controller", new {url_add} , null) %> 

,但是当我这样做,我的网址将为"blahblah.com/url_add=aa=strA"

任何人都可以告诉我更好的解决方案。

非常感谢。

回答

1

蒂蒂,

的问题是有关的事实,你正在尝试一个单一的财产“对象”添加到routevalues字典,即:

<%: Html.ActionLink("My link", "my_action", "my_controller", new {url_add} , null) %> 
在这种情况下

,要添加路径值:new {url_add},它完全是您构建的连接字符串。这个routevalue需要是一个keyvalue对,所以你连接和添加一个变量的方法是行不通的。

我建议你沿着在逻辑流程内创建一个全新的routevalues字典,并且只在最后的动作链接上添加它(即动作链接的构建只发生一次你的逻辑的最后一行)。

例如

var newRoutes = new RouteValueDictionary(); 
// if condition for strA matches 
newRoutes.Add("aa", strA); 
// if condition for strb matches 
newRoutes.Add("bb", strB); 

希望这给出了一些想法。

[编辑] - 响应下面您的意见,这是你所需要的过载,包括@class对象:

<%: Html.ActionLink("My link", "my_action", "my_controller", newRoutes, new Dictionary<string, object> { { "class", "selectedQ" } }) %> 
+0

感谢吉姆。无论如何,我必须将这块代码放入Global.asax.cs或其中? – titi 2012-02-09 10:03:27

+0

titi - 这个小块可以被添加到现有的代码,你定义的strA变量等 – 2012-02-09 10:19:28

+0

吉姆,我试图添加链接'<%:Html.ActionLink(“我的链接”,“my_action”,“my_controller”,新{newRoutes},null)%>',但url是'blahblah.com/My_controller/My_action?newRoutes = System.Web.Routing.RouteValueDictionary'。 – titi 2012-02-10 02:01:45