开发者

Insert two values into the url

开发者 https://www.devze.com 2023-04-05 01:25 出处:网络
I would like to insert the value from Request.QueryString[\"u\"] as a second parameter in the url below. So that the url read Item.aspx?id=1&u=2. But I can\'t get two server side tags to work with

I would like to insert the value from Request.QueryString["u"] as a second parameter in the url below. So that the url read Item.aspx?id=1&u=2. But I can't get two server side tags to work within the NavigateUrl value field.

<asp:HyperLink runat="server" 
               NavigateUrl='<%# Eval("itemID", "Item.aspx?id={0}") %>' /> 

I got errors doing it like this:

<asp:HyperLink runat="server" 
               NavigateUrl='<%# Eval("itemID", "Item.aspx?id={0}") %>
               <%= "&u="+Request.QueryString["u"开发者_开发百科].ToString() %>' 
/>


Try out following, not sure about syntax because can't check it now:

NavigateUrl='<%# String.Format(
                    "Item.aspx?id={0}{1}", 
                    Eval("itemID"), 
                    Request.QueryString["u"] == null
                    ? String.Empty
                    : String.Concat("&u=", Request.QueryString["u"].ToString())); %>'


You get errors in your second example because you cannot concatenate multiple <%# %> expressions within a single property.

I.e, the syntax is always: <tag property='<%# expression %>' />

An example for such an expression can be found in sll's answer. Since you added a question to his answer, I'll shamelessly steal his answer and add the feature you require:

I forgot. Sometimes Request.QueryString["u"] might be null and I also don't want the &u= in the url when it is null. I tried to move it into a variable outside the <%# &%>-tags, but then the variable won't be found inside the tag.

In that case, use a conditional (with the ternary ?: operator):

NavigateUrl='<%# "Item.aspx?id=" + Eval("itemID") +
                 (Request.QueryString["u"] != null
                  ? "&u=" + Request.QueryString["u"] : "") %>'

You don't need ToString, since QueryString["u"] already returns a string. What you should do, however, is to correctly encode the text, since the string might contain & or other special characters that "break" your URL:

NavigateUrl='<%# "Item.aspx?id=" + Eval("itemID") +
                 (Request.QueryString["u"] != null
                  ? "&u=" + Server.UrlEncode(Request.QueryString["u"]) 
                  : "") %>'
0

精彩评论

暂无评论...
验证码 换一张
取 消