ASP.NET Scope of user control for javascript functions - c#

So I have a user control that exists multiple times on a page. From the back end I can call userControl1.someFunction(); and specify which user control I want to call someFunction() for. But if I have a java-script function on the front-end of the user control I can't call it for individual user controls. All I have to do is call javaFunction(), but this doesn't specify which user control I want to call. So this is what I would like to be able to do, clientsideUserControl1.javaFunction(); Is this possible to do? What I have been doing is generating the function name dynamically IE: clientsideUserControl1_javaFunction(), but I feel like there has to be a better way to do this.

usually you can have one function and have it perform it's work on the whole page or you can change it to take a parameter ( a reference to the usercontrol you're interested in )
That way you don't need to have multiple copies of the same javascript function.
So instead of
function CLIENTID_javascriptFunction{
}
You'd have on function at the global level :
function javascriptFunction(id){
}
and call it with the id of the dom object you're interested in. (use ClientID to get the DOM id of the control)

Turns out that in this case it would be better to use a server control instead of a user control. Server controls seem to be a little more complicated to make but they do protect the scope of the javascript functions.
Here is a link that discusses the differences.
http://www.hotscripts.com/forums/asp-net/31174-difference-between-user-control-custom-server-controls.html

one possible solution is this:
function <%= ClientID %>javaFunction()
{
//code here
}
you will have a function declaration for each user control with the client ID of the control plus function name

Related

Page.Request in OnLoad of a Server Control

In the OnLoad of a server control I would like to do the following:
string username = Page.Request["UsernameTextBox"];
The actual controls are then created in CreateChildControls (so I will only need to do this on a postback).
The problem is that I cannot use the IDs in this way, because the control in this case must be referenced by name.If I hard code it i can solve the problem by doing this:
string username = Page.Request["ctl02$ctl00$ctl02$ctl00$ctl02$ctl03$ctl03$ctl02$ctl01"];
Of course this would be a bad solution considering that the control hierarchy could change. So my question is this: Is there a way for me to get this control name in OnLoad. If I could find the method that calculates the name from the NamingContainer or something i would be fine.
(Let's not discuss this wierd design in this login control/page - consider it as the constant of my question).
You can set the ClientIDMode property of your username textbox to static.
http://msdn.microsoft.com/en-us/library/system.web.ui.clientidmode.aspx

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.

Re-using another page section

I have created a web page that I use as a small dashboard to hold issue or no issue. It works great. The page uses an .aspx and .aspx.cs. I would like to be able to reuse the information on this page on other pages. My site already uses master pages and I have not been able to find an easy way to include this information.
How can I use an include from a page that has coding in the code behind easily?
Typically you use Web User Controls for this.
Web User Controls allow you to package up other controls into one that you can drop onto multiple pages. They are great for common UI items such as address entries, dashboards, etc. Basically anything that needs to be the same across multiple pages.
At the risk of seeming very obvious - do you mean usercontrols. These will allow you to reuse chunks of functionality across your site.
I guess this question falls into two categories: User Controls, and Code Reuse. Not sure which one you are after.
User Controls
If you are talking about the controls on your page you will want to create a common user control.
Code Reuse
You need to create a common class (whether it is static or not depends on how you intend to use it) and define functions within that class.
For instance, lets say you have a page that you want to print "Hello World!" on any aspx/.cs page.
You could do this
public static class MyClass
{
public string PrintHelloWorld()
{
return "Hello World!";
}
}
Then you call it from any of your pages like so:
MyClass.PrintHelloWorld();
Right click on the project > Add New Item...
Select User Control (.ascx)
Put your markup & code behind there.
Then you add that control in any other page (includding other controls [although I wouldn't recommend that])
It sounds like you may want to create an ascx User Control.
http://msdn.microsoft.com/en-us/library/ie/2x6sx01c.aspx

Filling a HTML form with C#

I need help with connecting to a certain website via my username & password.
With WebClient I can fill the username field and the password field, but how do I invoke the click method of the button?
And How can I fill a specific textBox that doesn't have an ID?
I tried doing this with webBrowser, but every time I navigate I have to use a new function every time, which makes the work much harder.
Thanks.
What you're trying to do is wrong. If you want to Post some data to a web address (a URL), simply create a web form (a simple HTML form), fill it, and then send it. Just consider these notes:
Your HTML's form action should be the exact URL of the form you're imitating.
Your input controls should have the same name attribute value.
For more information, see Form Spoofing
Look at the web browser control and see if you can use that inside your windows form to perform the task that you are doing. Once you are satisfied with the results, you can make the web browser control invisible, and it'll work just like you do with web response and request calls.
View the source code and find the id of the button (say "Login").
Then use:
HtmlElement elem = webBrowser1.Document.GetElementById("Login");
if (elem != null)
elem.InvokeMember("click");

Calling method on Master page from WebMethod

Or any viable workaround.
So, imagine a Master page that implements IFooMaster with a method ShowFancyMessagePopupTheBusinessCantLiveWithout(string message);
I am in a page that inherits this master page. Upon a checkbox being unchecekd, I want to show a message to the user that if they save it, they can't re-check the checkbox without some admin action.
I've been given feedback that I can't just use an alert('message'); in javascript because they want the consistent look of these messages.
Next, I tried to make an ajax call via PageMethods (as that's what everything else in this codebase uses) to show a message. My problem lies in this method being static.
[WebMethod]
public static void ShowSuperImportantMessage()
{
if(!checkboxICareAbout.Checked)
((IFooMaster)Master).ShowFancyMessagePopupTheBusinessCantLiveWithout("If you uncheck that thing, you can't recheck it.");
}
Since ShowSuperImportantMessage() is static, I can't access Master from within.
The method on the master page looks more or less like this:
public void ShowFancyMessagePopupTheBusinessCantLiveWithout(string message)
{
lblGenericMessage.Text = message;
btnGenericMessageOK.Focus();
upGenericMessage.Update();
mpeGenericMessage.Show();
}
mpeGenericMessage is an ajaxtoolkit:ModalPopupExtender.
upGenericMessage is an update panel.
The other 2 are obvious.
Any ideas? Can I do some jQuery kung-fu to show that stuff? I tried, but the solution complained that the controls I tried to refer to by ClientID didn't resolve since they were on the Master page.
quick edit: Before anyone tells me the architecture is a problem, or I shouldn't have put such a thing on a master page, or w/e...
I know the situation is not ideal, but I this is inherited code, and I can't drop it all and rewrite half of their web stack.
Try something like this (untested):
((IFooMaster) ((Page)HttpContext.Current.Handler).Master)
It appears this doesn't work - Master isn't hooked up when the PageMethod is called (makes sense).
So, instead, create an empty page using the same master page. Have that page accept either a POST or GET with whatever parameters you need to pass to your master-page method. Have the Page_Load extract the parameters and call the method. It should then use Response.Write to return a result (and remember to change the Content-Type). Have your client-side code call the page and get the result.
Did you try something like window.top before the ClientID?
Per comments
You don't need to hardcode ClientID. Since your js is in page, try something along the following lines....
window.top.document.getElementById( "<%= yourelement.ClientID %>" ).Whatever();
Sorry to take so long to respond/answer.
I'm not proud of this at all, mind you, but the eventual solution was to hardcode the client IDs into the jQuery that pulled up the modal dialog on the master page.
Like I said, I'm not proud of this dirty, dirty fix. However, the consolation is that, since it's on the master page, there isn't really any naming container above it. As such, it's much less likely to run into problems with the clientID changing.

Categories