Asp.net checkbox and html data attribute - asp.net

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

Related

Css works for html checkbox control and not for asp.net checkbox control

I have this html checkbox with css applied to it.
Here is the jsFiddle.
JsFiddle
It works perfectly , the problem is when i am trying to apply the same css to asp.net checkbox, it is not working.
Here is the code for html input control.
<input type="checkbox" name="chkReservaSemanal" id="chkReservaSemanal" class="css-checkbox" runat="server" /><label for="chkReservaSemanal" class="css-label">Week</label>
And here is the code with asp.net.
<asp:CheckBox ID="chkSemanal" runat="server" AutoPostBack="True" OnCheckedChanged="chkSemanal_CheckedChanged1" CssClass="css-checkbox"/>
But when applied to asp.net checkbox it is not working.
The css is on the jsFiddle.
Check the rendered code from ASP.NET. The CssClass that you define is added to a wrapper around the input and label controls.
So you can add css rules to compensate:
input[type=checkbox].css-checkbox,
.css-checkbox input[type=checkbox] { ... }
Or you can use code behind to attach the class names to the label and input controls separately:
chkSemanal.InputAttributes["class"] = "css-checkbox";
chkSemanal.LabelAttributes["class"] = "css-checklabel";
Web controls in the System.Web.UI.WebControls namespace may render differently in different browsers. You can't count on them rendering the same elements always. They may add anything that they think is needed to make it work in the specific browser.
For example, an asp checkbox:
<asp:CheckBox ID="CheckBox1" runat="server" CssClass="myClass" />
May render with a span:
<span class="myClass"><input id="CheckBox1" type="checkbox" /></span>
as you can see it's the span who have the classname and not the input type checkbox.
The best way to render it as you want is to use:
CheckBox1.InputAttributes.Add("class", "myCheckBoxClass")
Just to say:
CheckBox1.CssClass
will render the same way as adding a CssClass attribute and may add spans.
Hope this would be helpful, I faced this problem before and this is one of the ways to solve it.
As the asker didn't mention how he got it working, I'll share the solution suggested by #MALK:
<span class="css-checkbox">
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:Label ID="Label2" runat="server" Text="Click me!" CssClass="css-label" AssociatedControlID="CheckBox1"></asp:Label>
</span>
And to prevent style lost after a PostBack, in the Page.Load event:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.CheckBox1.InputAttributes("class") = "css-checkbox"
Me.CheckBox1.LabelAttributes("class") = "css-checklabel"
End Sub
Best regards.

Placeholder/Example text in textbox for user

What is the step to get example text to show up in an asp.net textbox.
For example, textbox w/ ID = "textboxDate" has [mm/dd/yyyy] inside it for the user to reference.
I believe you want a placeholder attribute:
<asp:TextBox ID="placeholderTextBox" runat="server" placeholder="mm/dd/yyyy"></asp:TextBox>
but placeholder doenst work for many IE browser because placeholder is html5 thing.
try to use modernizr framework. it works for all browsers including all IE
here is a sample code for you.
if(modernizr.input.placeholder) {
//insert placeholder polyfill script here.
}
Visual Studio maybe not knowing the attribute. Attributes which are not registered with ASP.net are passed through and rendered as is.
<asp:TextBox ID="TextBox1" runat="server" Width="187px" placeholder="mm/dd/yyyy"></asp:TextBox>
So the above code (basically) renders to:
<input type="text" placeholder="mm/dd/yyyy"/>
You can allways use:
<input ID="placeholderTextBox" type="text" runat="server" placeholder="mm/dd/yyyy" />
and on code behind you can get or set the value using
Dim myValue As String = placeholderTextBox.value or placeholderTextBox.value = "whatsoever"

HTML forms in ASP.NET

Hello all how to use HTML text field instead of ASP.NET textbox.?
How to write C# code to make use of HTML forms instead of ASP.NET
EDIT:
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<input id="Text1" type="text" runat="server" />
<asp:Button ID="Button5"
runat="server" Text="Button" OnClick="button5_click" />
<div>
<script runat="server">
protected void button5_click(object sender, EventArgs e)
{
Text1.Value = "Hello";
}
</script>
</form>
Instead of using or whatever server control, just type in the standard type tags or whichever HTML control you want.
If you want to be able to access them from your code-behind, then just include a runat="server" value with each HTML tag and make sure you give it an ID.
You need to retrieve the value from the HTTP request's Form collection:
<input type="text" name="MyTextField" />
Code behind:
string value = Request.Form["MyTextField"];
This question doesn't make much sense. You really should clarify and flesh out the question and explain what you are trying to do.
In some ways, an ASP.NET textbox is an HTML text field that C# code can make use of. So what's the problem with an ASP.NET textbox?
You can create an instance of a HtmlInput control in code, or alternatively add a runat="server" attribute to an <input> element in your aspx file, you can then access this from server-side code using it's ID.
As an alternative, you may wish to take a look at http://asp.net/mvc to get better control of your HTML markup.

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

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.

ASP.NET : Reading form variable values in the action page of search form

I have a website where i want to implement search functionality.So i added the below code to have a search box in my html page
<form id="search" method="post" action="Results.aspx">
<input id="txtSearchKey" type="text" name="txtSearchKey" />
<input id="Submit1" type="submit" value="submit" /><br />
<br />
</form>
In Results.aspx, I want to read the value user has entered in the txtSearchKey text box. What is the ideal way to do this ? I used
string strKey = Request.Form["txtSearchKey"].ToString();
But it throw a null reference exception.
I don't want to have all pages in ASP.NET.I want to have only the result page as ASP.NET
Could be because you do not have a NAME attribute on the textbox field. That's the value that is used as the key in the Request.Form collection. An input field without a name attribute will not be submitted, I think.
e.g.:
<input id="txtSearchKey" type="text" name="txtSearchKey" />
You can get your txtSearchKey field by this :
string strKey = PreviousPage.Request.Form["txtSearchKey"].ToString();
But, instead of using form action to forward your search to another page, you can use a button with PostBackUrl property like that :
<asp:Button runat="server" ID="btnSearch" PostBackUrl="Search.aspx" />
Because in ASP.NET, to have more then one form is not allowed.
Is there any reason you don't use
form runat="server"
and then drag a TextField and a Button in this form. Then doubleclick the button and write code you want.
If you want to do it your way you need to give your s a name="txtMySearchKey" for it to work
The way you are going about things is not really the way you work in ASP.NET web forms. The preferred way is to use asp.net server controls and events to abstract the process you are trying to achieve. For instance, your form should really be something like this (note the runat="server" attribute that enables you to reference the controls programmatically):
<form id="form1" runat="server">
<div>
<asp:Panel ID="PanelSearch" runat="server" DefaultButton="ButtonSubmit">
<asp:TextBox ID="TxtSearchKey" runat="server" /><br />
<asp:Button ID="ButtonSubmit" Text="Submit" runat="server"
onclick="ButtonSubmit_Click" /><br />
</asp:Panel>
</div>
</form>
Then, in your code behind you would handle the ButtonSubmit_Click event like this to enable you to get the value from the TxtSearchKey textbox:
protected void ButtonSubmit_Click(object sender, EventArgs e)
{
string strKey = TxtSearchKey.Text;
}
See the Quickstart example for the TextBox control for more info.
Just do not use .toString() after the Request.form... it will not give a null reference after that.

Resources