Control is set to visible false, jQuery selector fails - asp.net

Hi I have some controls on an asp.net modal which I show manually via code behind. Now I am trying to attach a selector on one of the controls inside pageLoad(), problem being is that the modal container is initially set to visible=false.
I tried checking for length but it still throws exception
if ($('#<%= myControl.ClientId %>').length > 0)
{
$('#<%= myControl.ClientID %>').click(function() {
// Do work
});
}
Compiler Error Message: CS0103: The name 'myControl' does not exist in the current context

A few things here, the first/main issue is that myControl isn't defined in the current scope, wherever you are in ASP.Net, that's entirely a .Net side problem.
For the Script, there are more issues, .ClientID, not .ClientId. Also, there's no need to check for it's existence, you can just do:
$('#<%=myControl.ClientID%>').click(function(){
// Do work
});
...if the control isn't there, it just won't find/bind anything. There's also an easier way to go about it in ASP.Net, if there's a unique class you can give it, just give add that class, e.g. CssClass="MyClass", then use that as your selector; like this:
$('.MyClass').click(function(){
// Do work
});
This allows you to put the script in an external file instead of the page as well, another benefit to the user.

Related

Hide aspx button in code behind

I am trying to hide an aspx button on page load if another element has a certain value.
Button:
<input type="button" class="formButton" id="btnShowTerminate" value="Terminate Credential" onclick="ToggleTerminationRow()">
My issue is that I don't know how to edit the buttons attributes (to make it hidden) in the code behind.
In code behind (on PageLoad event):
Page.btnShowTerminate.Visible = false;
HTML controls need to be given the runat="server" attribute in order to be used in the server-side code.
To hide the button from your code behind, use an If statement to test if your 'other element' has the required value.
C#
If(exampleElement.Value == "example value")
{
Page.btnShowTerminate.Visible = false;
}
VB
If exampleElement.Value == "example value"
Page.btnShowTerminate.Visible = false;
End If
This error -
'System.Web.UI.Page' does not contain a definition for
'btnShowTerminate' and no extension method 'btnShowTerminate'
accepting a first argument of type 'System.Web.UI.Page' could be found
(are you missing a using directive or an assembly reference?
is because you haven't included runat="server" in your input.
The exampleElement.Value may have to be different depending on what type of element exampleElement is. For example, Value will work with a TextBox , but you would need to use InnerHtml for a div
Although, a button (any control for that matter) can be hidden from code behind by setting the Visible property to false, there is subtle, and dangerous nuance to that. Doing this causes the button not only to be hidden, but the resulting HTML button will not render on the page. Should you have JavaScript that is referencing the button, the JavaScript will fail because the button does not exist on the rendered page. In debugging, the bug will be caught, but if the JavaScript is never exercised until the code is deployed to a server, it will fail there but no exception will be thrown. The code just won't work and there will be no indication as to why!
The safe way to hide the button is setting the Style as follows:
btnName.Style.Add("display", "none");
This way the button will be rendered but hidden and JavaScript will be able to find it.

GWT FormPanel and submitting data to server

I've a GWT app that I need to put FormPanel to wrap a textbox (TextBox). (to solve some styling issue)
EDIT:
The style issue is that: we are using some pre-build style sheet which put styles by HTML tag names .. so we need to put a form tag to wrap some components in order to be able to read the styles!
the problem is, on the KeyPress event, I notice there is a loading in the page appears. although the result returns ajaxaly as if there's no client-server trip happened.
The question is, How to remove this trip to server?
NOTE: i am just wrapping the componenets into the formpanel, I've not set any properties of it:
FormPanel formPanel = new FormPanel();
CaptionPanel captionPanel = new CaptionPanel();
formPanel.add(captionPanel);
captionPanel.add(horizontalPanel);
verticalPanel.add(formPanel);
Thanks.
From your question, it isn't clear that what is causing the trip to the server. But if it is the FormPanel that's causing this, I would change the instantiation of the FormPanel to the following:
FormPanel formPanel = new FormPanel() {
public boolean onFormSubmit() { return false; }
};
This should be the equivalent of the following html, which will keep the form from submitting:
<form onsubmit="return false">
If this doesn't fix it, you'll need to do some more debugging to see where the server is being called. The Tamper Data plug-in for Firefox might be of help for this.
The whole point of FormPanel is to create a classis HTML-style form submission. It should be used to achieve interoperability with servers that require form submission.
Don't use FormPanel just to solve "some styling issues".
OTOH, if you need to retrieve some data from the server, AJAX-style, than read http://code.google.com/webtoolkit/doc/latest/tutorial/JSON.html#http

Microsoft JScript runtime error: '(function name)' is undefined

Microsoft JScript runtime error: 'txtGivenName_OnFocus' is undefined
After adding what I thought was unrelated javascript code to a web page, I am suddenly getting errors that suggest that the browser cannot locate a javascript function that, to me, appears plain as day in design mode.
I'm thinking that this is a load sequence order problem of some sort. Originally, my script was at the bottom of the page. I did this with the intent of helping my site's SEO ranking.
When I moved the function to the top of the web page, the error went away. Now it is back.
I have a feeling someone is going to suggest a jQuery solution to execute some code only when the page is fully loaded. I'm I ignorant of jQuery. IfjQuery is given in the answer, please explain what I need to do (references, placement of script files) for VS 2010 RTM.
I am trying to set the focus to the first textbox on the webpage and preselect all of the text in the textbox
More info:
If I disable this Validator, the problem goes away:
<asp:CustomValidator ID="valSpecifyOccupation" runat="server" ErrorMessage="Required"
ClientValidationFunction="txtSpecifyOccupation_ClientValidate"
Display="Dynamic" Enabled="False"></asp:CustomValidator>
function txtSpecifyOccupation_ClientValidate(source, args) {
var optOccupationRetired = document.getElementById("<%=optOccupationRetired.ClientID %>");
if (optOccupationRetired.checked) {
args.IsValid = true;
}
else {
var txtSpecifyOccupation = document.getElementById("<%=txtSpecifyOccupation.ClientID %>");
args.IsValid = ValidatorTrim(txtSpecifyOccupation.value) != "";
}
}
Yep, I would say most likely it's a loading order issue as well. And... I would totally recommend jquery...
Wherever you are calling your JavaScript function txtSpecifyOccupation_ClientValidate; I would assume you are possible dynamically writing a script block to the page on load or something...
if this is the case. I would add the following to your generated script block...
$(function() {
... call to function
txtSpecifyOccupation_ClientValidate();
...
});
jquery is very easy to learn. http://docs.jquery.com/Main_Page

Flag control properties as required in design view

I'd like to force the consumer of a control to give a property a value when placing the control on a page.
In VisualStudio when you create an < img > tag without attributes SRC or ALT on a user control, it gets underlined saying that SRC and ALT are required attributes. I assume this is just a special handling of the tag by the editor, but is there a way to define a similar behavior for controls?
If the control had a property defined like this:
public object AProperty
{
get
{
if (ViewState["AProperty"] == null)
{
throw new Exception("AProperty is a required property of this control");
}
return ViewState["AProperty"];
}
set { ViewState["AProperty"] = value; }
}
Is there a way to use a Custom Attribute or something else that would flag in the designer?
You could use the Microsoft.Build.Framework.Required attribute. This would require a value to be set at build time or the build will fail with a message which indicates that the property does not have a value.
I don't believe there is an attribute to indicate that a specific tag must be included in a server control (or at least I don't see any such attribute on the System.Web.UI.HtmlControl.Image class). I believe that the litle underlines are part of the HTML validation of the IDE.
You could always create a custom attribute which throws a warning if a property is missing
While Microsoft.Build.Framework.Required is probably the best answer here, for others who stumble upon this and can't use .NET 4.0, you can also use this method:
http://forums.asp.net/t/1238319.aspx

Using JQuery as an ASP.NET embedded webresource

I have an ASP.NET server control which relies on JQuery for certain functionality. I've tried to add as a webresource.
My problem is my method of including the jquery file adds it to the body, or the form to be exact:
this.Page.ClientScript.RegisterClientScriptInclude(...)
The alternative to this is to add it as a literal in the head tag:
LiteralControl include = new LiteralControl(jslink);
this.Page.Header.Controls.Add(include);
The problem with this however is any existing code srcs in the head which use JQuery fail, as JQuery is loaded afterwards (ASP.NET adds the literal at the bottom of the control tree).
Is there a practical way of making JQuery an embedded resource, but loaded in the head first? Or should I give up now.
If you want to package up jQuery and embed it inside your own server control you should serve it to the client using the ScriptManager. From the top of my head you have to:
add jQuery.js to your project
under its "Build Action" Property,
make it an Embedded Resource
in the AssemblyInfo.cs for your
control add
[assembly: WebResource("<Your Server Control namespace>.jQuery.js", "application/x-javascript")]
Make your control inherit from
System.Web.UI.ScriptControl (or at
least implement IScriptControl)
Override GetScriptReferences:
protected override IEnumerable<ScriptReference>
GetScriptReferences()
{
return new ScriptReference[] {
new ScriptReference("<Your Server Control namespace>.jQuery.js", this.GetType().Assembly.FullName),
};
}
All of your own client script should be setup inside:
protected override IEnumerable<ScriptDescriptor> GetScriptDescriptors()
Which will then ensure the correct order of dependencies (ie jQuery will be available to your own client script).
Update:
A far easier way of doing it is to simply add the script tag dynamically, in your script and point to the google code hosting. e.g.
function include_dom(script_filename) {
var html_doc = document.getElementsByTagName('head').item(0);
var js = document.createElement('script');
js.setAttribute('language', 'javascript');
js.setAttribute('type', 'text/javascript');
js.setAttribute('src', script_filename);
html_doc.appendChild(js);
return false;
}
include_dom("http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js");
The function is taken from this article
Crecentfresh pushed me in the right direction, I also found
http://en.csharp-online.net/Creating_Custom_ASP.NET_AJAX_Client_Controls—IScriptControl.GetScriptReferences_Method.
My problem still remains though, the ScriptManager adds the references after the script in the head but I think this is an issue that can't be resolved. I've opted to answer myself but also upvoted crescentfresh.

Resources