ASP.NET How do I add javascript function to a control? - asp.net

I have some user controls that I want to add some client side functionality to.
Let say 1 control has a hidden field and a bunch of checkboxes. When a checkbox is checked, it sets the hidden field to 'YES'. How could I $get that control in the hosting control or page, and call some function on it that would return the value of that hidden field?
If I have a couple of these on the page, I'd like to be able to do this:
var choices1 = $get('choices1_id')
if(choices1.dirty() = 'YES')
//do whatever
var choices2 = $get('choices2_is')
if(choices2.dirty() = 'YES')
//do whatever
I might be looking for something like this: http://jimblackler.net/blog/?p=23 but I'm not sure how to access the object(s) from the parent.
thanks,
Mark

I take it the problem you are running into is that ASP.Net can mangle the id of the control?
In that case What I normally do is either note how the id is mangled for simple pages, and write the javascript accordingly, or for more complex scenarios I'll check the .ClientID property of each control and put it into variables in a custom script that's easily accessible to the rest of the javascript on the page.
This should be easier than it is, and not having simple access to every control element from javascript is one of my complaints with the ASP.Net framework. They're doing a little to address this in the next version, though not as much as they could. In the mean time, you can find various components on the web that will help automate generating the script I described above.

Related

How can I find and interact with a user control on a page from a separate user control?

I have an aspx page that has two different user controls. I want to find user control A and be able to set properties, etc., from user control B.
I was thinking I could do something like this:
Dim CMFilters As Control = Me.Parent.FindControl("CMFilters")
...but that doesnt work to be able to set properties and call methods. I somehow need to get the user control and and declare it as that user control type.
You should not make control A dependent of control B.
Instead, read and write the properties of both controls from the page that contains the controls.
So expose all properties you want to set in both controls A and B as public properties (read/write or read-only) and connect them e.g. in the Page_Load event of your page.
There's an article here explaining how to do it.
I would like to note that this is not considered a good design. This is the type of thing that's referred to as a "code smell". As a general rule of thumb, objects should be designed so that they are unaware of other objects, and can function independently of other objects.
A better approach would be to simply let the objects do what they do independently, and let the page class handle the interactions, since each is a child element of the page.
This design is listed as a code smell here:
http://www.codinghorror.com/blog/2006/05/code-smells.html
Inappropriate Intimacy
Watch out for classes that spend too much time together, or classes
that interface in inappropriate ways. Classes should know as little as
possible about each other.

How to change html view of web user control

I am creating a web user control for a simple poll. I am currently registering it on the page and then referencing it via tagprefix.
The form for the poll is in basic html (no server controls) and is in the front-end of the web control. How can I change the look of the user control depending on the settings passed into it? Is this possible without using server controls?
Update
Can I change the html layout of a user control? If so could someone post some examples. Please note I do not use asp.net form controls, so none of that please :)
You might be able to also use jQuery to replace existing css setting in your code. Create properties on for your user control, and then pass settings in the classes. Then use jQuery to replace them. This however requires jQuery to be linked to your page (or within your control) and you'd have to write the CSS classes out to the jQuery code (using server controls, but you could use the literal control so there's no excess code).
Personally I'd go with the option of using server controls instead of straight up HTML, you'd get alot more flexibility, and then passing through the settings would be pretty straightforward, put something like this in your controls backend code:
Private _TextBoxCssClass As String
Public Property TextBoxCssClass() As String
Get
Return _TextBoxCssClass
End Get
Set(ByVal value As String)
_TextBoxCssClass = value
txtBox1.CssClass = value
txtBox2.CssClass = value
End Set
End Property
You most likely want to have a property or event in the control that changes the css. It may end up best to add some server controls or javascript / jquery to make it easier.
If its only the styles you want to change, then you can expose a property to set the style attribuites of the respective control inside your User Control. If you want to control the whole HTML layout of the control then Custom Control is the viable option.

JQuery and ASP.NET Web Forms

I am creating a ASP.NET Web Form application where I am trying to use some nice jQuery functionality and flashyness. The current part of the application I have consists of two jQuery UI tabs; a search tab and a results tab. When the user performs a search from the search page, the results tab will be selected and the results will be displayed in this tab. I need to get the results into a gridview. Now this is where the issue starts to come in:
The easiest way to get the search results is to allow the search click to perform the postback where I can then format the datasource with the parameters from the input fields and let the datagrid take care of itself and data bind and show the results. The thing is, this really doesn't look that great (due to the whole post back and such) as well as starts to cause some issues with using javascript/jQuery to take care of tab switching and all that portion because the postback reinitializes everything from the jQuery UI (i.e. the jQuery UI tabs). So in short, the postback allows for easy binding of the input for the search and getting the results, but makes the page and its behavior all wonky.
I was wondering if there is a standard way to do this type of mixing jQuery/javascript/AJAX all together within web formto get the functionality of things like the gridview and such. I am wondering if there are some good tutorials, or even just a direction on solving this issue.
I hope all this made sense, and thank you all for your help.
I don't think this is a standard, but here is the pattern I use:
First of all, I use Page Methods for ASP.Net to get hooked back up to the server. In this case it would be something like this:
PageMethods.Search(searchValue, onSearchComplete);
That calls a static page method in the page, like this:
public static void Search(string searchValue)
...
Inside that procedure, I create an instance of a user control which contains the gridview, and invoke a method on that control, passing the searchValue:
var searchControl = (SearchControl)new SearchControl().LoadControl("/controls/SearchControl.ascx");
searchControl.Search();
var stringBuilder = new StringBuilder();
using (var textWriter = new StringWriter(stringBuilder))
{
var htmlWriter = new HtmlTextWriter(textWriter);
searchControl.RenderControl(htmlWriter);
return stringBuilder.ToString();
}
This is all going to end up as the result argument to the handler you specified in the initial call (onSearchComplete) in this example. You can do whatever you want with the markup, including slapping it into a div, or alerting it for debugging.

Copy info from one dynamically created user control to another dynamically created user control

My ASP.NET WebForm has a place holder on it and user controls are dynamically added to it. The controls mostly have textboxes. Sometimes there are two user controls, sometimes there are ten. Everything is working as expected. My question is about how to implement a new feature.
My customer has a new request to copy data from the first control to another control checking a checkbox associated with the additional control in question.
At first, this sounded easy... Add a checkbox to the placeholder for each user control and then write some JavaScript to copy the data from the first control to the additional control. Then I realized that by those textboxes being in a user control, I don't really have access to modify the HTML inputs directly.
Next I started thinking about adding checkboxes that will automatically post back, but how do I go about dynamically adding a checkbox to a placeholder, and then come up with a way to add event handler to the checkbox and pass in the information necessary to loop through the controls and copy the values. This approach seems way too complicated with too much overhead to accomplish my goal.
Any suggestions?
You mentioned that since the checkboxes are in a user control, you don't have access to them.
Could you expose the ClientIDs using a property of the user control and then work with them in javascript? Something like this:
user_control {
int checkboxId { get { return checkbox.ClientId; } }
}
If you have more code that would be helpful...
This is probably too late to help you, but just so another answer is out there...
Including the checkbox as a part of the user control simplifies the issue considerably.
I had a similar situation, with maybe 10-15 UI controls in a user control, with a checkbox associated with the first one which, when checked, meant that I should copy the info from the first user control to all of the others.
Since it was all built in the codebehind, I simply exposed a boolean property of the user control named ShowCheckBox, which toggled the visibility of the checkbox. I set this to true in the first one, and false in all of the others. Thus, I knew that the event could only be raised by a click of the first user control's checkbox. Then, in the event handler for the checkbox, I handled the copying from the first user control to all of the others. (By the way, be sure to set AutoPostBack=true on that checkbox or you'll wonder why the event isn't firing.)
Javascript would definitely provide a better user experience, but this worked for me and didn't require me to figure out how to get the ClientId values into the javascript. (Although that's exactly what I need to do now, which is how I stumbled upon this question. :-) )

Are hidden fields on child window inaccessible from parent window

I have asp.net form that contains fields. When I access this window, my javascript functions can access the fields via the DOM with the getElementById() method and when I postpack to the server I am receiving the updates made by the client.
However, when I launch the form as a child window using Telerik's RadWindow control, the javascript can not access the hidden fields on the child form. Instead I get null.
My questions are:
Are hidden fields on a child window
not accessible when the window is
launched from a parent asp.net form?
Has anyone attempted this with Telerik controls and run into issues?
EDIT
Craig pointed out that the id may be different. Two additional questions then:
Can you ensure that the id you assign at the server is actually used?
Is using getElementByName() a better mechanism to access DOM elements?
To get the ID of your asp.net control do something like this:
<%= theControl.ClientID %>
getElementByName is not as commonly used as getElementById. The ID attribute is supposed to be unique for each element on the page whereas the name attribute can be duplicated.
It is quite possible that the element's ID is not what you think it is. Check the rendered page and see if the ID is there. I am guessing that the page is given a different ID since it is rendered inside another control.
If that is the case, you can have the form render some script that returns the element ID by accessing the controls client ID.
David, I'm sending you this answer because I saw the same issue in my code, and the only REAL solution I found was that I had to support the "OnClick" function in two places... In my case, I was using PetersDatePackage, but it was on a Telerik RAD Strip.
In my case, the control was on a .ascx page, and the JS code was as follows:
function OnIncidentDateChange(ctrl, dtDate, bErr)
{
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
<%=LabelDayOfWeek.ClientID %>.innerText = weekday[dtDate.getDay()];
}
But, this itself was not enough. I had to add THIS code to my parent page. The page that holds the controls for the Telerik strip.
// Dummy function?
function OnIncidentDateChange()
{
}
Once I did that, it worked...
I'm not certain why, to tell you the truth, and it makes no sense to me, and may just be a issue with the PDP package...
I use getElementsByName for checkboxes within the same group.
As for the control's ID, TonyB has the right idea, but make sure you refer to the ClientID property in the PreRender event handler, because if you do it too early in the page life cycle, it will not be available yet).
Is it possible the that javascript is trying to get a reference to the hidden field before the RadWindow has loaded it? I believe I've run into this before and had to use setTimeout to get around the problem.

Resources