Forcing client ids in ASP.NET - asp.net

I know that in the next version of ASP.NET we'll finally be able to set the clientids on System.Web controls without the framework doing it for us in a quasi-intelligent way e.g:
id="ctl00__loginStatus__profileButton"
Does anyone know a good method in the meantime to force the above id to something like
id="profileButton"
The main reason for this is manipulation of the clientids in jQuery when dynamically adding controls to a page. The problem I can see is changing the ids will break the Viewstate?

You have to use the ClientIDMode attribute:
<asp:xxxx ID="fileselect" runat="server" ClientIDMode="Static"/>

What I tend to do is dynamically generate javascript methods which handle this. You can do this in markup or code behind so for example:
<script language="javascript" type="text/javascript">
function doXYZ()
{
$("#" + getListBoxId()).css(...)
}
function getListBoxId()
{
return "<%=this.myListBox.ClientId>";
}
</script>
You can also build the functions in the code behind and register them.
EDIT
A couple months ago I needed to fix the id of some server controls, I managed to hack it in and I described my method here here.
Basically you need put the controls inside a naming container like a user control, and then override a couple of properties which prevents the child controls from getting their uniqueid.

The performance isn't great, but you can use this selector syntax to match messy ClientIDs:
$("[id$='_profileButton']")
That matches any element ending in _profileButton. Adding the leading underscore ensures that you're matching the desired element and not another element that ends in the substring "profileButton" (e.g. "myprofileButton").
Since it has to iterate over the entire DOM, the performance can be poor if you use it in a loop or several times at once. If you don't overuse it, the performance impact is not very significant.

Another way would be to wrap your control with a div or span with a static id, then access the control through that.
E.g.
<span id="mySpan">
<asp:TextBox id="txtTest" runat="server" />
</span>
You could then target input tags inside MySpan. (though I agree it would be nice to be able to specify a nice name, provided you could handle the naming conflicts...)

I have often run in to this "problem" while developing in asp.net webforms. In most cases I tend to use the css class of the element.
jQuery(".My .Container12")
Before starting to manipulate the id:s, perhaps that is a way you can handle it aswell? It's a simple solution.

There is another solution not mentioned which is to subclass the ASP.NET controls and force the IDs:
public class MyCheckBox : CheckBox
{
public string ForcedId { get;set; }
public override string ID
{
get
{
if (!string.IsNullOrEmpty(ForcedId))
return ForcedId;
else
return base.ID;
}
set
{
base.ID = value;
}
}
public override string ClientID
{
get
{
return ID;
}
}
}
Then use this where you know the IDs will never clash:
<mytag:MyCheckBox ForcedId="_myCheckbox" runat="server" />
If you are using lists you will need to write a ListControlAdapter, and also adapters for each type of list you're using (dropdown,checkbox,radiobutton,listbox). Alternatively cross your legs and wait for .NET 4.0.

Related

Disabling every input on a page programmatically in ASP.NET

I have tried searching around for this, but what I found was mainly for disabling a single input type.
What I want to do is disable every input type on a single page. Everything. Textboxes, checkboxes the whole lot.
I couldnt figure out how to modify the loops I found, which is why I am asking here, beacause it's likely one of you has a piece of code laying around that can do it.
Thank you in advance.
try below if you like to do it in javascript/jquery
$(document).ready(function(){
$('input').attr('disabled','disabled');
});
OR try below if you want in asp.net
ach control has child controls, so you'd need to use recursion to reach them all:
protected void DisableControls(Control parent, bool State) {
foreach(Control c in parent.Controls) {
if (c is DropDownList) {
((DropDownList)(c)).Enabled = State;
}
DisableControls(c, State);
}
}
Then call it like so:
protected void Event_Name(...) {
DisableControls(Page,false); // use whatever top-most control has all the dropdowns or just the page control
} // divs, tables etc. can be called through adding runat="server" property

asp.net 4.0: is there any equivalent of ClientIDMode for the names of INPUTs?

I have an asp:ListView whose ClientIDMode is set to Predictable. Its ItemTemplate contains an asp:textbox.
The ID of the textbox is acting as I expect it to, but its name is still using what looks like an AutoID-style algorithm:
<input name="lvFields$ctrl0$tbVal" id="lvFields_tbVal_somekey" type="text"/>
Is there a way for me to cause the name of the input to act like the ID does?
(Edit in response to questions below:)
The Name of the input element is what's in the POST data, so if a postback alters the list to which the ListView is bound (for example, exchanging two elements) the values from the textboxes end up associated with the wrong keys, because the framework is correlating them based on the Name and not the ID.
You can change the name of an Input by using the method from the following post but modifying it slightly:
how to remove 'name' attribute from server controls?
I over-rode the RenderChildren method on a Page control as I just wanted full control of the HTML for a few controls:
protected override void RenderChildren(HtmlTextWriter writer)
{
var unScrewNamesRender = new RenderBasicNameHtmlTextWriter(writer);
base.RenderChildren(unScrewNamesRender);
}
private class RenderBasicNameHtmlTextWriter : HtmlTextWriter
{
public RenderBasicNameHtmlTextWriter(TextWriter writer) : base(writer) { }
public override void AddAttribute(HtmlTextWriterAttribute key, string value)
{
if (key == HtmlTextWriterAttribute.Name && value.Contains("POLine"))
{
value = value.Substring(value.LastIndexOf("$") + 1);
}
base.AddAttribute(key, value);
}
}
You do need to know what you're doing if you attempt this, WebForms will think the control is missing so you can't use it in any postbacks. For my purposes, where I wanted to add an arbitrary number of multiple lines either server or client-side without having to deal with .Net Ajax controls, it works fine.
I'm pretty sure you can't change the name, especially when you modify the ClientIDMode. As an alternative, you can add a Title attribute. VS will flag this as unknown in the server side code, but it renders correctly in the HTML. If you're doing some client-side manipulation, you can address the input as such:
<script type="text/javascript">
$(document).ready(function () {
$('input:text[title="TextBoxName"]').datepicker();
});
</script>
As far as I know, there is no way to change the name of the input element. The name corresponds to the UniqueID property, which is generated by the system, and which you have no control over. Seems you have to find a way to achieve what yo want using only the control ID.
Both names are using the predictable pattern; originally, name also equaled ct100_ct100 etc. From what I see, that's a predictable name. Client ID value will always use _ between control prefixes and Unique ID (name attrib) will always use $. The two will always match, except for a few controls that leverage name for something (radiobuttonlist uses for grouping).
HTH.
I had the exact same problem once and had to use one of these properties exposed in "System.Web.UI.Control" to get clientside control name in server side.
Play around with these properties and construct the "Name" in server side yourself and use Request.Form("NameHere")
Me.ClientIDSeparator
Me.IdSeparator
Me.UniqueID
A jquery solution
function removeNameAttribute() {
$('input, select').each(function () {
$(this).removeAttr("name");
});
}
//Use a HtmlGenericControl
HtmlGenericControl input = new HtmlGenericControl("input");``
input.ID = "lvFields_tbVal_somekey";
input.Attributes.Add("name", "tbVal");
input.Attributes.Add("type", "text");
input.ClientIDMode = ClientIDMode.Static;

How to get the radiobutton for corresponding datalisty item?

I want to convert this code to JavaScript code:
rdb1 = (RadioButton)DataList1.Items[i].FindControl("rdb1");
How can it be done?
Put a unique class on the radio button and then you can easily use jQuery to walk the DOM and find that control.
Here is an example of finding a control here on Stack Overflow.
Here is a tutorial of How to Get Anything You Want from a web page via jQuery.
Good luck, and hope this helps.
In JavaScript using the id attribute makes it easy to retreive a specific element since the id must be unique for all tags.
var radio1= document.getElementById("rdb1"); //this returns the element
Here is a simple tutorial on how to do other things after getting the element.
EDIT- I see you just want the selected value in javascript:
function radiochanged(){
var radio1= document.getElementById("rdb1");
var rdb1_value;
for (i=0;i<radio1.length;i++)
{
if (radio1[i].checked)
{
rdb1_value = radio1[i].value;
}
}
}
<input id="rdb1" type="radio" onClick="radiochanged()">

Setting multiple literals that contain the same text in ASP.NET

I have instances where I need to dynamically load 5-10 literals with the same text value. It seems like there has to be a more elegant way of doing it than setting the TEXT property of all the controls to the same value. Any methods out there that I'm not aware of? I thought about setting a protected property on my webform, and then using inline code on my aspx page. Is that a good approach?
Edit: I should add that I also want to handle the situation where a designer could simply add another place to load dynamically to the aspx file on the web server without having to do another rollout.
Pseudo code:
var literals = new List<Literal>() { l1,l2,l3 ...} ;
literals.ForEach(x=>x.Text = "some value");
When faced with the same problem I often use:
litOne.Text = litTwo.Text = litThree.Text = "some value";
It's not perfect but at least it's on one line.
How about this?
foreach (ITextControl textControl in new[] { literal1, literal2, literal3 })
{
textControl.Text = "foo";
}
You could even be fancier and just loop through all controls and check only those that implement the ITextControl interface or so.

disable asp.net validator using jquery

I am trying to disable validators using jquery.
I have already looked
Disable ASP.NET validators with JavaScript
and couple of others doing the same.
It seems ot be working but its breaking.
My code:
$('.c_MyValdiators').each(function() {
var x = $(this).attr('id');
var y = document.getElementById(x);
ValidatorEnable(y[0], false);
});
I get Error:
val is undefined
[Break on this error] val.enabled = (enable != false);\r\n
Alternatively if I use
$('.c_MyValdiators').each(function() {
ValidatorEnable($(this), false); OR ValidatorEnable($(this[0]), false);
});
I get Error:
val.style is undefined
[Break on this error] val.style.visibility = val.isvalid ? "hidden" : "visible";\r\n
Any idea or suggestions?
I beleive that ValidatorEnable takes the ASP.net ID rather that the ClientID produced by ASP.net. You will also need to make the validation conditional in the CodeBehind.
here is an example:
Of particular use is to be able to enable or disable validators. If you have validation that you want active only in certain scenarios, you may need to change the activation on both server and client, or you will find that the user cannot submit the page.
Here is the previous example with a field that should only be validated when a check box is unchecked:
public class Conditional : Page {
public HtmlInputCheckBox chkSameAs;
public RequiredFieldValidator rfvalShipAddress;
public override void Validate() {
bool enableShip = !chkSameAs.Checked;
rfvalShipAddress.Enabled = enableShip;
base.Validate();
}
}
Here is the client-side equivalent:
<input type=checkbox runat=server id=chkSameAs
onclick="OnChangeSameAs();" >Same as Billing<br>
<script language=javascript>
function OnChangeSameAs() {
var enableShip = !event.srcElement.status;
ValidatorEnable(rfvalShipAddress, enableShip);
}
</script>
Reference: http://msdn.microsoft.com/en-us/library/aa479045.aspx
I just stumbled upon your Question [a year later].
I too wanted to disable all validators on a page using JQuery here is how I handled it.
$('span[evaluationfunction]').each(function(){ValidatorEnable(this,false);});
I look for each span on the page that has the evaluatefunction attribute then call ValidatorEnabled for each one of them.
I think the $('this') part of your code is what was causing the hickup.
ValidatorEnable(document.getElementById($(this).attr('id')), true);
I've got another solution, which is to use the 'enabled' property of the span tag for the validator. I had different divs on a form that would show or hide so I needed to disable the validation for the fields inside the hidden div. This solution turns off validation without firing them.
If you have a set of RequiredFieldvalidator controls that all contain a common string that you can use to grab them the jquery is this:
$("[id*='CommonString']").each(function() {
this.enabled = false; // Disable Validation
});
or
$("[id*='CommonString']").each(function() {
this.enabled = true; // Enable Validation
});
Hope this helps.
John
I'm just running into the same problem, thanks to the other answers, as it helped uncover the problem, but they haven't gone into detail why.
I believe it is due to that ValidatorEnable() expects a DOM object (i.e. the validation control object) opposed to an ID.
$(selector).each() sets "this" to the DOM element being currently iterated over i.e. quoted from the jquery documentation:
"More importantly, the callback is fired in the context of the current
DOM element, so the keyword this refers to the element." - http://api.jquery.com/each/
Therefore you do not need to do: document.getElementById($(this).attr('id')
And instead ValidatorEnable(this, true); is fine.
Interestingly, Russ's answer mentioned needing to disable server side validation as well, which does make sense - but I didn't need to do this (which is concerning!).
Scrap my previous comment, it is because I had my control disabled server-side previously.
The ValidatorEnable function takes an object as the 1st parameter and not a string of the id of the object.
Here is the simple way to handle this.
Add a new class to the Validation control.
Then look for that class with jquery and disable the control.
Example :
if (storageOnly == 1)
{
$('#tblAssignment tr.assdetails').addClass('hidden');
$('span[evaluationfunction]').each(function ()
{
if ($(this).hasClass('assdetail'))
{ ValidatorEnable(this, false); }
});
}
else
{
$('#tblAssignment tr.assdetails').removeClass('hidden');
}
* Works like a charm.
** For you imaginative types, assdetail == assignment detail.
Here depending on the if condition, I am either hiding the rows then disabling the validator , or removing hidden class from the rows..
Various ways to this depending on your needs. Some solutions in the following blog posts:
http://imjo.hn/2013/03/28/javascript-disable-hidden-net-validators/
http://codeclimber.net.nz/archive/2008/05/14/How-to-manage-ASP.NET-validation-from-Javascript-with-jQuery.aspx

Resources