Imran Rizvi
Imran Rizvi

Reputation: 7438

How to append selected dropdownlist value to hyperlink querystring in aspx page itself

I have a dropdownlist.I want to add selected value of it to a hyperlink querystring .How Can i do this from aspx file itself using <% %> block? My code is like this

<asp:DropDownList ID="ddlLanguage" runat="server" DataSourceID="ds" DataTextField="Langcode" DataValueField="LangKey" Width="200px"> </asp:DropDownList>

<% if (ddlLanguage.Items.Count>0) { %>
  <asp:HyperLink ID="hlnk" NavigateUrl="abcd.aspx?lkey=1" runat="server" />
<% } %>

How can i pass the selected value of dropdown list to NavigateUrl of hlnk.

Please don't answer to use aspx.cs file. I want it to done on the sameline only.

Upvotes: 0

Views: 2525

Answers (2)

Richard
Richard

Reputation: 22026

The problem you face is that the action occurs on the client side and so you will need to adjust the value of the link when the dropdown change occurs using javascript (I have used jQuery here for ease).

You could implement a jquery based function to monitor the dd for a change and then set the url of the link.

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>

<body>
...
    <asp:DropDownList ID="ddlLanguage" runat="server" DataSourceID="ds" DataTextField="Langcode" DataValueField="LangKey" Width="200px"> </asp:DropDownList>

    <% if (ddlLanguage.Items.Count>0) { %>
     <a href="abcd.aspx?lkey=1" id="hlnk>Link to other location</a>
    <% } %>

    <script>
      var ddId = '<%=this.ddlLanguage.ClientID %>' 
       $('#'+ddId).change(function () {
           $('#hlnk').attr('href', 'abcd.aspx?lkey='+$(this).val());
       });
    </script>

...
</body>

Upvotes: 1

Richard
Richard

Reputation: 8280

To update the NavigateUrl dynamically without modifying the .cs file you could write a client side OnChange event for the drop down list, that simply updates the href attribute for the output hlnk control by prepending the selected value.

This could easily be achieved using jQuery. Here is some sample code to get you started.

$('.language-dropdown').change(function()
{
    var newUrl = 'http://www.example.com/?id=' + $(this).val();
    $('.hyperlink').attr('href', newUrl)
});

Alternatively, for performance, you could re-locate to the correct url using a hyperlink that looks like a hyperlink, but acts using JavaScript. This would mean the url is only changed once, instead of every time.

$('.hyperlink').click(function()
{
    var newUrl = 'http://www.example.com/?id=' + $('.language-dropdown').val();
    window.location(newUrl);
});

Upvotes: 1

Related Questions