how to set Name attribute for HiddenField control server-side? - asp.net

I want to set the "name" attribute for HiddenField control of ASP.NET from code behind, but I cannot find the "Attributes" property. Is it not there for a purpose? How do I add the attribute?
thanks

The name attribute is automatically computed from the ID properties of the hidden field and its ancestors in the naming container chain. You don't get to set it yourself. You can only access it through the UniqueID of the control.

A possible solution, without knowing a bit more about your code, is to use a server side Html control rather than an ASP.NET web control by adding the runat="server" attribute to the Html markup:
<input type="hidden" id="myHiddenField" runat="server" />
You can then specify the id dynamically in the code behind at runtime from which the name attribute is inferred from:
myHiddenField.ID = "CodebehindName";
myHiddenField.Value = "myValue";
This will result in the following output:
<input name="CodebehindName" type="hidden" id="CodebehindName" value="myValue" />

Another unorthodox method to deal with it is to set the name attribute client side. This is useful if you are posting to a third party such as PayPal.
jQuery EG:
<script type="text/javascript">
$(function () {
$('#BusinessHid').prop('name', 'business')
$('#CurrencyHid').prop('name', 'currency_code')
$('#InvoiceHid').prop('name', 'invoice')
$('#AmountHid').prop('name', 'amount')
})
</script>
<asp:HiddenField ID="BusinessHid" runat="server" ClientIDMode="Static" />
<asp:HiddenField ID="CurrencyHid" runat="server" ClientIDMode="Static" />
<asp:HiddenField ID="InvoiceHid" runat="server" ClientIDMode="Static" />
<asp:HiddenField ID="AmountHid" runat="server" ClientIDMode="Static" />

Forget about the HiddenField control and use a Label instead, give it a name (an id), make it invisible, and store your text into it:
label = new System.Web.UI.WebControls.Label() {
Text = "Here my hidden text",
};
label.Attributes.Add("id", "MyHiddenFieldID");
label.Attributes.Add("style", "display:none;");
myParentControl.Controls.Add(label);
Get your hidden field in your javascript with:
var myHiddenField = document.getElementById("MyHiddenFieldID");

The way I ended up doing this was to set ClientIDMode="Static" on the HiddenField and then set the ID to what I want my name to be.
I ended up with ugly IDs but this was a small price to pay to get this to work.

Related

how to copy text from an asp:textbox to another asp:textbox in asp.net webfroms aspx

I've been trying to find a solution for hours now.
asp:textbox 1:
<asp:TextBox runat="server" ID="code" placeholder="<%$ Resources:ErrorMessages, EnterCode %>" CssClass="enterCode"></asp:TextBox><br />
asp:textbox 2:
<asp:TextBox runat="server" ID="code2" placeholder="<%$ Resources:ErrorMessages, EnterCode %>" CssClass="enterCode"></asp:TextBox><br />
button:
<asp:Button CssClass="btn btn-primary" runat="server" ID="buttonEnable2" OnClick="buttonEnable_Click" Text="<%$ Resources:UserMessages, Enable %>" />
I'm trying to copy text from textbox 2 into textbox 1.
textbox 2 is embedded in a jquery accordion in a bootstrap popover.
I've tried:
the simple one within aspx.cs:
code.text = code2.text;
some jquery within a javascript file linked to the aspx file:
$("#buttonEnable2").click(function () {
$('#code').val($('#code2').val());
alert('test');
});
the code above doesn't seem to work at all, it doesn't even give me an alert.
The problem is that you're using an accordion inside of a popover which clones everything inside the popover, coping the ID of everything. So when you type a value into the textbox it attaches it to the clone of the textbox, not the actual textbox.
here's the solution:
function clickEnable2() {
var txtBox1 = this.parentElement.getElementsByClassName("enterCode")[0].value;
$("#MainContent_code").val(txtBox1);
$("#MainContent_buttonEnable").click();
}
$("#MainContent_buttonEnable2").click(clickEnable2);
This Code is in javascript
<script>
function Copy() {
var n1 = document.getElementById('code');
var n2 = document.getElementById('code2');
n2.value = n1.value;
}
</script>
and your button should be like
<asp:Button CssClass="btn btn-primary" runat="server" ID="buttonEnable2" OnClientClick="Copy()" OnClick="buttonEnable_Click" Text="<%$ Resources:UserMessages, Enable %>" />
Hope it will help.
Your textboxes are of asp.net which changes the ID of textboxes with respect to its ContentPlaceHolder. So jquery is unable to find the textboxes.
You can use ClientIDMode="Static" so that ID of textboxes will not change. Put this property for the other textbox as well.
<asp:TextBox runat="server" ID="code" ClientIDMode="Static" placeholder="<%$ Resources:ErrorMessages, EnterCode %>" CssClass="enterCode"></asp:TextBox>
Then use jquery to copy text from one textbox to other.
$('#code').val($('#code2').val());
If you are using master pages, update panels etc in asp.net, the ID of the text box will be automatically replaced with a dynamic ID, hence you may need to do the following, this will help if you do not want to change the ClientIDMode to Static
First declare a javascript variable and assign your textbox's dynamic id's to it, for which the JQuery will be
$(document).ready(function(){
var txtBox1 = <%=code.ClientId%>;
var txtBox2 = <%=code2.ClientId%>;
});
Now you can use these two variables to copy your text into one another
$("#buttonEnable2").click(function () {
$('#' + txtBox1).val($('#' + txtBox2).val());
});
You can also use the document.getElementById in the following way.
var n1 = document.getElementById(<%=code.ClientId%>);
var n2 = document.getElementById(<%=code2.ClientId%>);
I hope this will help you.

Asp.net checkbox and html data attribute

In asp.net, if you use a custom attribute, usually it is rendered as-is.
Considering this markup (note: attributes such as id, name and for were removed in all examples as their generated id/names are verbose):
<asp:TextBox runat="server" data-foo="bar" />
Is rendered in asp.net as:
<input type="text" data-foo="bar" />
That is, asp.net keeps data-foo untouched.
Check box are usually rendered like this:
<asp:CheckBox runat="server" Text="Normal" />
Renders as:
<input type="checkbox" />
<label>Normal</label>
But if you add a custom attribute on a checkbox:
<asp:CheckBox runat="server" Text="Custom attribute" data-foo="bar" />
It renders as:
<span data-foo="bar">
<input type="checkbox" />
<label>Custom attribute</label>
</span>
As you can see, a span in rendered to hold the attribute. This also happens if you add the attribute in code behind. This does not happen with any other HtmlControl, AFAIK.
Does anyone know why this span is rendered to hold the attribute?
Is there anyway to render the attribute in the input tag?
I'm not sure why it's rendered with a span, but I suppose you can add the attribute directly to the input element of the CheckBox in code-behid like this:
myCheckBox.InputAttributes.Add(...)
Reference links:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox.inputattributes.aspx
http://forums.asp.net/p/541142/541562.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.attributecollection.add.aspx
Update
An additional parent element is used, so that the attributes you apply to a CheckBox can affect both the input and the text. I suppose it's a span (and not a div), because it's an inline element, making it more convenient to use in different scenarios.
Reference links:
http://en.wikipedia.org/wiki/Span_and_div#Differences_and_default_behavior
http://learnwebdesignonline.com/span-div
This is the way that render engine builds the CheckBox control, there isn't very much to do about it.
Something you could do is creating a runat="server" input.
<input id="myInput" runat="server" type="checkbox" data-foo="bar"/>
<label>Custom attribute</label>
Another option is adding the data-foo attribute using jquery on document load
$(function(){
$('span[data-foo]').each(function(){
var $span = $(this);
var value = $span.data('foo');
$span.find('input').data('foo',value);
});
})
Just to add another method that I use when all else fails, you can always use a literal control and make it render whatever you want. You need to do a bit more work when handling the postback, but sometimes this is the only way to get the html you need.
Markup:
<asp:Literal ID="myLiteral" runat="server"/>
Codebeside:
myLiteral.Text = string.Format("<input type=\"checkbox\" data-foo=\"{0}\" /><label>Normal</label>", value)
If you are trying to access that attribute on click event you can do that by casting the control. For example I have a check box and I assign it a custom attribute like you did
<asp:CheckBox runat="server" data-foo="bar" />
Now on OnCheckedChanged I need to get that value and in my method I got a sender object.
protected void chk1_CheckedChanged(object sender, EventArgs e)
{
CheckBox myControl = (CheckBox)sender;
string value = myControl.Attributes["data-foo"].ToString();
}
I hope this help someone

How can I use Client ID within a server control?

I was able to do the following in a repeater and it works just fine:
<asp:TextBox ID="txtOtherPartyName" Text='<%# Eval("Name") %>' runat="server" />
<asp:RequiredFieldValidator ID="reqLoss" ControlToValidate="txtOtherPartyName"
data-valmsg-for='<%# Container.FindControl("txtOtherPartyName").ClientID%>'
Display="Dynamic" ErrorMessage="Name of party involved is required." runat="server" />
The data-valmsg-for attribute in the required validator rendered the server control id just fine. How can I do the same for a control that sits on a page and is not within a repeater? I tried similar things without any luck.
Update
So here's what I'm looking to do exactly:
<asp:Textbox id="txtTest" runat="server" />
<asp:RequiredFieldValidator id="reqTest" data-valmsg-for=**[i want the html rendered id of "txtTest" here]** runat="server" />
You can bind that custom attribute to the control's client id in the code behind.
butthead.Attributes.Add("data-custom-prop", beavis.ClientID);
In the Repeater you used databinding syntax (<%# ... %>), but that doesn't apply in this case. You should be able to set the attribute like this:
data-valmsg-for='<%= TextBox1.ClientID %>'
Why are you adding custom attributes to the validators in the first place though, if you don't mind me asking? What purpose does it serve that can't be achieved through other means?
EDIT
Have you considered building your list of control IDs in code-behind beforehand, and storing it somewhere? Could something like this be a starting point?:
var controlList = Page.Validators.OfType<BaseValidator>()
.Select(v => Page.FindControl(v.ControlToValidate).ClientID).ToList();
EDIT
Expanding on that idea, you can serialize the list to JSON using the JavaScriptSerializer (System.Web.Script.Serialization):
//initialize the javascript serializer
var serializer = new JavaScriptSerializer();
//retrieve all of the validators on the page and store the client ids in a list
var controlList = Page.Validators.OfType<BaseValidator>()
.Select(v => Page.FindControl(v.ControlToValidate).ClientID).ToList();
//serialize the control id list and register the script block on the page
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "data", string.Format("var data = {0}", serializer.Serialize(controlList)), true);
Depending on how complex the form is, you may need to create a recursive function to find all of the controls, but hopefully this demonstrates the concept.

User Control Static Name Option?

I know there is a way to force asp web user controls (ascx) to use static ID's so they don't get appended with all the appended naming garbage...but is there way to do the same for the"name" attribute? Specifically, in this case, for DDL's? JQuery needs a specific name and I need to stop .NET from doing this.
Not possible in ASP.Net for now ... I've found this combination to be an acceptable solution.
Add the ClientIDMode="Static" to the control:
<asp:HiddenField ID="HiddenField1" runat="server" ClientIDMode="Static" />
Using JQuery, on document ready, set the name attribute on the control to the value of its id:
$(document).ready(function () {
// alert($("#HiddenField1").attr("name"));
$("#HiddenField1").attr("name", "HiddenField1");
// alert($("#HiddenField1").attr("name"));
});
Try adding ClientIDMode="Static" to the control tag.
<asp:FileUpload ID="FileUpload1" runat="server" ClientIDMode="Static" />

Assigning hidden field to a variable

I have an aspx control as follows
<input type=""hidden"" value='EmployeeId' id=""employeeID""/>
I need some help in making the value of the above hidden field dynamically assigned to a integer variable called EmoployeeId somewhere above this line. Can anyone point out how to do this?
Thanks
Add runat="server" to the markup:
<input runat="server" type="hidden" value="" id="employeeID"/>
And on code behind, do this:
employeeID.Value=valueFromVariable.ToString();
If you've ASP.NET then use server control,
<asp:HiddenField id="empId" runat="server" value="10"/>
and in code behind,
int no=int.Parse(empId.Value);
//Or - use int.TryParse
You can assign a server-side variable to a client-side Javascript variable as so (Classic ASP):
<script type='test/javascript'>
var myVar = '<% =myServerVar %>' <--- a string
var myNum = <% =myServerVarNUm %> <--- a number
</script>

Resources