Set the html 'name' attriubute of an asp:DropDownList - asp.net

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.

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.

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.

Related

Dynamic file upload controls not working in asp.net webforms page

I have a web page where I dynamically generate lots of elements from code behind and inject them into the page, as such:
input type="file" style="width:480px;" id="fileUploadLogo345">
I also have buttons for submitting, like this:
input id="Submit1" type="submit" value="Substituir Logo" onclick="return jsSubmitLogo(345);">
(The javascript function always returns true...)
No matter what I try, I am unable to get any of the uploaded files from code behind.
I tried adding enctype="multipart/form-data" to the form, I tried adding runat="server" to the file upload controls, I have no idea what else I could try. No matter what I do, in code behind Request.Files.Count equals zero.
Any idea what I could be doing wrong?
If it makes any difference, I am using a master page...
Thanks
You are using "id" attributes in your html... you should instead use "name" attributes, and everything will show up fine in code behind.

hyperlink.NavigateUrl getting changed on master page (possibly by ResolveUrl() )

I have a hyperlink that in certain cases I want to change to show a jquery popup, but I'm having a strange problem when doing it on a master page. The following works in a regular page:
hyp1.NavigateUrl = "#notificationPopup";
Which renders as:
<a id="ctl00_hyp1" href="#notificationPopup">Example</a>
This is exactly what I want. The problem is with the exact same code on a hyperlink on the master page it renders as:
<a id="ctl00_hyp1" href="../MasterPages/#notificationPopup">Example</a>
It looks like it might be running the navigateUrl through ResolveClientUrl() or something when I'm setting it on the master page. I've tried swapping the <asp:hyperlink for a <a href runat=server, but the same thing happens.
Any ideas?
There is a note on MSDN Control.ResolveClientUrl method description.
The URL returned by this method is
relative to the folder containing the
source file in which the control is
instantiated. Controls that inherit
this property, such as UserControl and
MasterPage, will return a fully
qualified URL relative to the control.
So the behavior of master page in your exampe is fully predictable (although this is not a very comfortable to work with). So what are the alternatives?
The best one is to set the <a> as a client control (remove runat="server"); should work like a charm even in a master page:
Example
In the case if this control should be server side only: you could just build an URL from your code behind by using UriBuilder class:
UriBuilder newPath = new UriBuilder(Request.Url);
// this will add a #notificationPopup fragment to the current URL
newPath.Fragment = "notificationPopup";
hyp1.HRef = newPath.Uri.ToString();
Create a hidden field on your form and set the value to where you want to navigate / the url of the hyperlink instead of the hyperlinks navigate url. Then call the onclick method of the hyperlink in javascript and set the hyperlink there before the browser does the actual navigation.
<html><head><title></title></head>
<script type="text/javascript">
function navHyperlink(field)
{
field.href = document.getElementById('ctl00_hdnHypNav').value;
return true;
}
</script>
<input type="hidden" id="hdnHypNav" value="test2.html" runat="server"/>
<a href="" onclick="navHyperlink(this);" >click here</a>
</html>
Code behind would be:
hdnHypNav.value = "#notificationPopup";
You could also just try setting the url after the postback with below code, i.e. replace your code behind line with this one but I am not sure if it will work...
ScriptManager.RegisterStartupScript(this,this.GetType(),"SetHyp","$('ctl00_hyp1').href = '#notificationPopup';",True)
I found another way to solve the problem.
hyp1.Attributes.Add("href", "#notificationPopup");
Seeing as the whole reason I replaced my static hyperlink with a runat="server" one was to benefit from automatic resource-based localization, none of these answers served my needs.
My fix was to enclose the hyperlink in a literal:
<asp:Literal ID="lit1" runat="server" meta:resourcekey="lit1">
Example
</asp:Literal>
The downside is if you need to programmatically manipulate the link, it's a bit more annoying:
lit1.Text = String.Format("Example", HttpUtility.HtmlAttributeEncode(url));

Checking a radio button with jQuery when radio button is runat="server"?

Using jQuery I want to be able to click an element which will also checks it's related radio button. I had this working fine until we had to add runat="server" to the radio buttons.
When I apply this it prevents my jQuery function from working and I cant figure out how to get round it, heres a simplified version of the code:
HTML
<input type="radio" runat="server" id="sector1Radio" name="SectorGroup" title="Sector1" />
jQuery
$('#SomethingElse').click(function() {
$('input[title=Sector1]').attr('checked','checked');
});
I've found out that when its converted to a .net control instead of checked="checked" (as it would be usually) it is just Checked, so I changed that but on inspecting the DOM in multiple browsers, none of my radio buttons are being checked :-(
Are there any other ways I can use jQuery to check a radio button that has runat="server"?
Cheers!
I think that Your problem is that the id of the input is no longer sector1Radio but rather ctl00_sector1Radio or something similar. This happens if Your input control is inside e.g. a ContentPlaceHolder control (when using master pages).
Can You check the generated HTML code (in the browser) to verify if this is the case? What is the id of the input control?
If this is the case, You need to generate Your js jQuery code
$('#SomethingElse').click(function() {
$('input[title=Sector1]').attr('checked','checked');
});
from codebehind so that SomeThingElse is replaced with the ClientID of the control.
.is(':checked') works on ASP.NET radiobuttons and checkboxes
$('#SomethingElse').click(function() {
$('input[title=Sector1]').is(':checked');
});
try using
$('input[title=Sector1]').attr('checked',true);
and
$('input[title=Sector1]').attr('checked',false);
or maybe
$('#SomethingElse').click(function () {
$('input[title=Sector1]').attr('checked',!$('input[title=Sector1]').attr('checked'));
});
As suggested by others, ASP.net will not generate the html with the same ID you specified.
Quick solutions:
You can keep using the id but asks jquery to check the end of the id instead, example:
$("input[id$='sector1Radio']").is(":checked");
Or check against the title and name as Nico suggested
Use the class element which is not effected by ASP.net, example
<input type="radio" runat="server" id="sector1Radio" class="sector1Radio" name="SectorGroup" title="Sector1" />
$("input.sector1Radio").is(":checked");
Best thing is to view the generated html code and see what id is giving you, then you can use the appropriate jquery selector, because the generated id could have different extensions depends whether you use master pages, etc.
If you are using a MasterPage or are creating the controls dynamically then it is probable that the control ID's are being renamed #SomethingElse becomes #MainContent_SomethingElse.
The easiest way to check this is to use the WebDeveloper plugin for Firefox or Chrome.
Go to Information -> Display Element Information and then select the object in question. It will give you it's ID, class, as well as ancestor and children information.
Check to see if the ID is being changed dynamically by the .NET.
If that's the case:
To prevent this, in the server side code you can use the following attribute to create static ID's
SomethingElse.ClientIDMode = ClientIDMode.Static;
You can then reference in you jQuery
$('#SomethingElse').click(function() {
if ($('input[title=Sector1]').attr('checked')) {
//execute event
});
I think what happens is that in ASP NET Checkboxes and Radio Buttons generates an "input" and a "span" after the input. So you need to select the input only.
You can try:
$('.classname input[type=checkbox]').each(function() {
this.checked = true;
});
Two things here: finding the control and executing the check. In ASP.NET, your control's actual ID and name will end up getting changed based on the runat="server" containers in which it appears, even if those containers have no Ids.
Rendered ASP.NET controls always end with the same name as you started with, so a tag like:
<input type="radio" runat="server" id="sector1Radio" title="Sector1" />
might end up being rendered as
<input type="radio" runat="server" id="ctl0$ctl0$sector1Radio" name="ctl0_ctl0_SectorGroup" title="Sector1" />
You can find this element, even after it is rendered if you use the "contains" selection syntax in JQuery. So to find this element, once rendered, you could use:
$("input[type='radio'][id*='$sector1Radio']")
This syntax will find any radio button whose id contains "$sector1Radio"
Once you have the element, you can check or uncheck it using the following code, which you'd call from the click event of your other element.
// check the radio button
$("input[type='radio'][id*='$sector1Radio']").attr('checked', true);
// uncheck the radio button
$("input[type='radio'][id*='$sector1Radio']").attr('checked', false);
One last thing... if you just want a block of text to click the button when pressed (wrap it in an tag and set the AssociatedControlId property to the control name of your radio button, like this...
<input type="radio" runat="server" id="sector1Radio" title="Sector1" />
<asp:label runat="server" id="lblsector1Radio" associatedControlID="sector1Radio">clicking here clicks and unclicks the radio button</asp:label>
I had the same problem. To use the jQuery UI to make your radiobuttons nice one has to write:
<div id="radio">
<input type="radio" id="radio1" runat="server" />
<label for="radio1">The label of the radio button</label>
...
</div>
<script type="text/javascript">
$('#radio').buttonset();
</script>
The id of the input tag must be correctly referenced by the label's for attribute. If the webpage is inside a master page then the id of the input tag will be modified to something like ctl00_Something_radio1, and suddenly the label's for attribute no longer references the input tag. Beware of this in ASP.NET!

How do I set the target frame for form submission in ASP.NET?

I have an asp.net page in an iframe where all links target _blank
<base target="_blank" />
But I want the form on it to submit to _self (i.e. the iframe where the page is located) when the one button is clicked. The form is an <asp:Panel> with an <asp:Button> control for submitting it.
Where can I set the target for this form? Since there isn't a <form> tag or an <input> tag in the file (ASP.NET makes them when it renders the page), I don't know how to change the target to override my <base> tag.
I'm not sure if I understood you right, but you can set the target in the form tag, like this:
<form method=post action="Page.aspx" target="_self">
I just found this post on the asp.net forums by mokeefe that changes the target by javascript.
I just put it in my page and tried it. I had to make these modifications:
1. I'm using asp tags only, so I have <asp:Button> not <input type="button"> and my onclick has to be the server-side method I'm calling on submission. Therefore I put this new javascript in OnClientClick:
<asp:Button ID="cmdEmailSearch" runat="server" Text="Search"
OnClick="cmdEmailSearch_Click"
OnClientClick="javascript:pageSubmit()"/>
2. I removed the myForm.submit() since ASP.NET renders the page putting the WebForm_DoPostBackWithOptions() javascript in the button's onclick right after it puts my pageSubmit()
<script type="text/javascript">
function pageSubmit(){
// where form1 is the Parent Form Id
var myForm = document.getElementById('form1');
myForm.target = '_self';
}// end function
</script>

How to control usercontrol from javascript

I have an usercontrol with an attribute targetUrl. I add this user control to a page and write targetUrl attribute from this page like below:
<PBG:Modal ID="Modal1"
runat="server"
Height="180"
Width="500"
src="pop_adres_giris.aspx"/>
This worked properly, but I want to change the targetUrl attribute from javascript. And I can't do it. I write code like below, but it didn't work.
var frm = document.getElementById('Modal1');
frm.targetUrl = 'pop_adres_giris.aspx';
How can I do it?
The UserControl object, which generates HTML on the client side, are not accessible as the rich objects which are available when handling server side calls.
Depending what the UserControl is, you will need to use a different method to get it and set the "targetUrl".
In addition, to ease your accessing of elements within the DOM you may want to consider using a library such as jQuery or prototype
Once you have declared your control, for instance, if you were using an asp:Hyperlink control:
<div id="hyperlink_holder">
<asp:Hyperlink ... NavigateUrl="http://someurl" />
</div>
You know that asp:Hyperlink generates html like <a href="http://someurl" ... />
So we can access the element and change the link like:
$('#hyperlink_holder a').attr("href", "http://newurl");
In addition, note that the ID you give an item in ASP.NET is not necessarily the ID which will render in the id element in the HTML; it is instead a concatenation of a number of ids; therefore use selectors based on non runat="server" controls where possible, or pass the ClientID of the UserControl through to the client to use for selection if absolutely necessary.

Resources