BenMills
BenMills

Reputation: 1095

Set the html 'name' attriubute of an asp:DropDownList

I have a asp:DropDownList element that I need to reference in my code behind but I need it to have a very specific name that has special characters so I cannot use that as the id.

Is it possible to manually set the name in the .aspx file? When I try to do it now:

The html is rendered with two name attributes.

Upvotes: 5

Views: 3626

Answers (2)

Michael
Michael

Reputation: 2414

While not exactly as OP requested, the name attribute can be changed using JavaScript or jQuery after the page is loaded. This is assuming you can put the desired name elsewhere. For example, say you set the Class attribute of the DropDownList to "MyValue123", you could then add a JavaScript on-click handler either on page load or on Submit (the following assuming jQuery support):

<select class="MyValue123">
</select>    

<script type="JavaScript">
    function fixSelectNames(){
        $("select").each(function(){
            $(this).attr("name", $(this).attr("class"));
        });
    }
    $(document).ready(function(){
        fixSelectNames();
    });
</script>

<input type="submit" value="Go" onclick="fixSelectNames();" />

Naturally the JavaScript code could be written via ASPX so that it contains the correct values for "MyValue123". When placed in a Submit button's JavaScript on-click handler, the code will execute before the parameters are posted by the browser, resulting in the server receiving the value under an updated name.

Upvotes: 0

Hna
Hna

Reputation: 1006

The name attribute is automatically generated which means you can't set it. But you can access it through the ClientID property of the control.

Upvotes: 1

Related Questions