C# Get id of dynamically created labels - c#

I need to be able to set the IDs of dynamically generated labels instead of letting SharePoint prefix my labels with a long cryptic id of its own. Is this possible or is there another property of label that I can use as a unique identifier in a separate method?
Label animal = new Label();
animal.ID = cat;
The id for this label will be something like:
ctl00_m_g_e0c173c0_edf3_4a99_a1dd_7bef33144c0b_ctl00_cat
I need it to be cat.

To force the client-side id to be the same as the server-side id, use:
animal.ClientIDMode = ClientIDMode.Static;

You cannot set the ClientId of a server control. It is a read only property.
The cryptic id you see is actually your control heirarchy.

If you're attempting to access the control with javascript and are using jQuery, you can just the various regex selectors:
$("label[id$='cat']")
That will look for a label element with an id that ends with 'cat'
If your javascript is in the aspx file, and not a js file, you can also access it like so:
$('#<%=cat.ClientID %>')
That will just inject that long id created by Sharepoint into your js. Key is it needs to reside in the aspx file, not a js file.

Related

JQuery set value to custom made server control

We have a custom made server control which several properties defined in it.
<cc1:DropdownCheck ID="ddcStatus" runat="server" CssClass="ddlchklst" JQueryURL="~/Scripts/jquery.js"
Title="Select Status(es)" OpenOnStart="false" divHeight="17px"
ImageURL="Images/DropDown.PNG" >
</cc1:DropdownCheck>
How can I set the value of the Title property on a click event of the server control. My current jquery fn looks like this...
$("#ddcStatus").click(function () {
//$('#ddcStatus').attr("Title",'Items Selected');
//document.getElementById("ddcStatus").Title = 'Items Selected';
});
Both statements didnt work. The getElementById statement gave a script error saying object null.
Problem is in your selector
"#ddcStatus" is use to select element with id ddcStatus but it is not same at clint side.
You Wil see it something like "abc_xzy_ddcStatus"
ID get changed when page load at client side. so you have two option to solve it
In browser go to source code by selecting view source or by inspect element and find
new ID in source and use that ID in jQuery
(I don't recommend this way)
use something called dynamic selector which server ID and convert to Client ID by self
$('DropdownCheck[ID$="ddcStatus"]')
you can read this as "select in DropdownCheck whose id ends with ddStatus"
Your solution will not be same replace DropdownCheck with actual control used at client side
some help for start with and end with style of jquery
http://api.jquery.com/attribute-ends-with-selector/
http://api.jquery.com/attribute-starts-with-selector/#attributevalue
Try doing something like that:
$(function(){
$("#ddcStatus").click(function () {
//$('#ddcStatus').attr("Title",'Items Selected');
//document.getElementById("ddcStatus").Title = 'Items Selected';
});
})

Get child controls on server control using javascript ASP.NET

I've create a basic composite server control that contains a button.
<Custom:Class1 ID="testClass" ClientInstanceName="test1" runat="server"></Custom:Class1>
I would like to be able to get to the child controls using javascript for example:
var myButton = testClass.FindControl('btnTest');
Is there anyway to do this?
Create a client side object to represent your server side control (javascript class). Put a collection of references to the child controls on the client side object. Then on the server side OnPreRender event create or load a script to define your client side object and at the same time pass the collection of references to its constructor.
Example of how to embed a javascript file containing the clientside object definition (put this somwhere above the namespace declaration:
[assembly: WebResource("myNS.stuff.clientSideObj.js", "application/x-javascript")]
namespace myNS.stuff
{
Example of how to register the WebResouce (OnPreRender):
ClientScriptManager cs = this.Page.ClientScript;// Get a ClientScriptManager reference from the Page class.
Type csType = this.GetType();// Get the type from this class.
//Register an embedded JavaScript file. The JavaScript file needs to have a build action of "Embedded Resource".
String resourceName1 = "myNS.stuff.clientSideObj.js";
cs.RegisterClientScriptResource(csType, resourceName1);
Example of creating a script to declare an instance of your client side object (OnPreRender):
String childControlIDsList= getChildControlList();//I am not writing this one.. just look up javascript arrays.
String uniqueScriptKey = "myKey";
StringBuilder theScript = new StringBuilder();
theScript.AppendLine("var myObj = new clientSideObj(" + childControlIDsList + ");");
theScript.AppendLine("window['myClientControl'] = myObj;") //create a client side reference to your control.
cs.RegisterStartupScript(csType, uniqueScriptKey, theScript.ToString(), true);
I will leave the client side object definition up to you... Hope that helps!
This is for Sharepoint visual web controls, but the same general process applies:
http://lemonharpy.wordpress.com/2011/07/20/expose-clientid-to-javascript-in-sharepoint-2010-visual-web-control/
Essentially, in the code behind on the page you get a reference to the ClientId on the page, and then expose that up as a javascript variable that you can prepend onto your jQuery selectors.
I feel this is a little hacky - but I think it gets the job done...
If you're using .net 4.0 you can set the the 'ClientIDMode' property on the button to Static then set the ID property to something like ID="myButton" and access it with with jquery like so
$("#myButton")
If you dont use jquery you can use
document.getElementById("myButton")
If you are using the control multiple times in the form you could prefix the button id with your custom controls id. Remember to set your custom controls ClientIDMode property to static as well.
<asp:Button ID="<%=Me.Id%>_myButton " ClientIDMode="Static" runat="server"/>
Not entirely sure this is even good practice or if it will work but you can try it.( remember to set your custom controls id

Dynamically change value of hidden field

For an existing site, I have to pass values in hidden fields from a form that's loaded by different pages (eg. City1.aspx, City2.aspx, City3.aspx, etc.), but they are loaded inside an iframe. I also have to dynamically change the value of at least one of those hidden field (let's call it "source") based on the city page loading it. I am familiar with PHP and JavaScript/JQuery, but I have no idea how to do this in C#.
I've found tutorials on retrieving the file name (sans extension) via JavaScript. I think I can still get the city even if the form is in an iframe, but I'd like to keep to the site's conventions and use C# if possible.
Code snippets or links to possible solutions would be much appreciated.
if you want modify the value of your input in c# associated to your aspx (Code behind), you must to add attributes runat=server to your input.
use this code in your aspx
<input id="test" type="hidden" runat="server"/>
and in your c#
test.Value = 123; //your value is 123 for example
Disclaimer, I don't know JQuery, so there could be easier ways to do this. I also haven't tested any code...
If you know the exact ID then you can do something like this from the parent page (in a javascript block):
var frame = document.getElementById('myIFrame');
var ctrl = frame.document.getElementById('myControl');
ctrl.value = "New Value";
If you don't know the exact ID's of the controls in the CityX.aspx pages, then you will either need a way for those ID's to be discovered, or you will need to go through all controls within the iframe looking for the correct one. (I say this because if the controls in the iframe pages are held in any sort of ASP.NET structure they will not be called txtMyCtrl (for instance) but possibly something like ct00_txtMyCtrl.)
If you don't know the EXACT control name (because of the ASP.NET structure I mentioned before), you could do something like:
var frame = document.getElementById('myIFrame');
var ctrls = frame.document.getElementByTagName("INPUT");
for(var i=0;i<ctrls.length;i++){
if(ctrls[i].getAttribute("type")=="hidden" && ctrls[i].id.indexOf("_myControl") != -1){
ctrls[i].value = "New Value";
break;
}
}
Or if you have the ability to update the CityX.aspx pages, then you could have the following in the CityX.aspx page:
function getCtrls(){
return [document.getElementById("<%=hiddenCtrl.ClientID%>"),
document.getElementById("<%=anotherHiddenCtrl.ClientID%>")];
}
... and then in your parent page, something like:
var frame = document.getElementById('myIFrame');
var ctrls = frame.document.getCtrls();
for(var i=0;i<ctrls.length;i++){
ctrls[i].value = "New Value";
}
They're just ideas on a general theme

Is there way to associate a function to usercontrol

Is there way to associate a javascript function to a user control? Lets say I have a name control written in .ascx. Can I define a client side function, lets say .clear(), that would be associated to name control. The clear function would clear all the elements of that control. I know I can create clear() javascript function but that would be global javascript function, not necessarily tied to name control. I want to tie the function to name control so that given that I have reference to name object, I should be able to simply call that function from that reference something like:
name.clear();
I know this can be done using MS Ajax framework but was wondering if I can do something like that using jQuery.
If by "clear" you mean set the value of text/password inputs, textareas and select elements to an empty string, and set radio and checkboxes to !checked, then you can do something like this:
$("#someid").find('select,textarea,input[type="text"],input[type="password"]').val('');
$("#someid").find('input:radio,input:checkbox').prop('checked',false);
Or as a plugin:
(function( $ ) {
$.fn.clearChildren = function() {
this.find('select,textarea,input[type="text"],input[type="password"]').val('');
this.find('input:radio,input:checkbox').prop('checked',false);
return this;
};
})( jQuery );
$("#someid").clearChildren();
Demo: http://jsfiddle.net/nnnnnn/AvfUz/
(jQuery does have an ":input" selector that selects all selects, textareas and inputs, but you don't want to set the value of checkboxes and radios so they need to be done separately.)
The user control itself is not rendered as an actual html element, but any of the parts of the user control that's actually rendered as an html element can be referenced from client scripts.
You need to write the control client id to the html from the page or the user control like this:
<script type="text/javascript">
$('#<%= TheControl.ClientID %>').clearChildren();
</script>
The jQuery function for clearing the children is defined in #nnnnnn's answer.

How do I get the correct ClientID for my ASP.NET TextBox?

I have created a a subclass of Table in my ASP.NET project which creates. The table uses a class that formats and creates TableRows and TableCells which we can call RowCreator. So MyTable calls rowCreator.CreateRow() and gets back a TableRow with a lot of goodies in it.
In this TableRow there is a TextBox which is supposed to trigger a javascript method on the onblur event, which is added by the RowCreator class.
textBox.Attributes.Add("onblur", "javascriptMethod('" + textbox.ClientID + "');");
I've also tried created a subclass of textBox which implements a method that adds the onblur event:
Attributes.Add("onblur", "javascriptMethod('" + this + "');")
Which doesn't work. The ID is just the namespace of the textbox subclass.
And the JavaScript method is very simple:
function javascriptMethod(boxId) {
alert(boxId);
}
The trouble is, and I'm guessing this is because the textbox control hasn't been added to the control collection yet, that the boxId isn't the proper client ID. It is the same as the server side ID. Is there a way of getting the proper ID without having to add the row using Controls.Add on the page first? Any other suggestions?
The reason I'm even doing this is to read the textbox contents from a javascript function whenever it's been changed. Maybe there's a better way to do this?
You could change the javascript call to this:
textBox.Attributes.Add("onblur", "javascriptMethod(this);");
Then you can access the textbox in your javascript method:
function javascriptMethod(textbox) { alert(textbox.id); }
That way you won't need to use the ClientID of the textbox control.

Categories