How to hide custom control after certain time - asp.net

I have a custom control which displays results of some operations.
It is hidden by default and its made visible on the code-behind of some other class.
Now I want to hide it after a certain amount of time. How do I do it?
Edit:
Some answers suggested adding following javascript block at the end of the custom control which is not working if Visible="false" is used on the custom control.
But I did not made that clear enough and so accepted that as an answer.
Have to take a look at: How to call javascript function from code-behind
The timeout function is correctly called if Visible="true" is used.
ASPX:
<control id="customControl" runat="server" Visible="false"/>
Solution if Visible="true" is used in markup:
Custom control - ASPX:
<div id="body">
<!-- custom control -->
</div>
<script type="text/javascript">
window.setTimeout(function() { document.getElementById('<%=Me.divBody.ClientID%>').style.display = 'none'; }, 2000);
</script>
Custom control - Code-behind:
Me.customControl.Visible = True
Solution if Visible="false" is used in markup:
From start the script block is not rendered and later is not added automatically. So we need to register it.
Custom control - ASPX:
<div id="divBody">
<!-- custom control -->
</div>
<script type="text/javascript">
window.setTimeout(function(){ alert("test"); });
</script>
Custom control - Code-behind:
Me.customControl.Visible = True
Dim hideScript AS String = "window.setTimeout(function() { document.getElementById('" & Me.divBody.ClientID & "').style.display = 'none'; }, 2000);"
ScriptManager.RegisterClientScriptBlock(Me.Page, Me.GetType, "script", hideScript, True)
Source: http://www.codeproject.com/Tips/85960/ASP-NET-Hide-Controls-after-number-of-seconds

I haven't seen any reference to jQuery in the question, hence vanilla JS solution:
Put this at the end of the User Control file
<script type="text/javascript">
setTimeout(function(){
document.getElementById("<%=this.ClientID%>").style.display = "none";
}, 5000);
</script>

You could have a property on the object which when executed changed the visible property to false if you were outside of a stipulated time frame, so you'd have a visible from and until field and have that generate a boolean when compared to the current time.

You can probably use the javascript setTimeout function to execute some code to hide the div which has the user control to hide after a time period
<div id="divUserControlContainer">
//put your user control embed code here
</div>
<script type="text/javascript">
$(function(){
window.setTimeout(function() {
$("#divUserControlContainer").hide();
}, 2000);
});
</script>

You achieve it by simple JQuery methods:
$("#CustomControl").hide(1000);
$("#CustomControl").show();

Related

Popup message box in c#

I'm looking for a custom user control similar to http://www.how-to-asp.net/messagebox-control-aspnet/ but having the ability to be displayed as a popup. The message box should have the capability of being invoked from code behind in asp.net 4 with event hooks to bind the "ok" and "cancel" button.
I'm familiar with Ajax Toolkit and JQuery.
A reference and or sample in a similar direction would be very helpful.
Thanks!
Use jQuery UI. They have great examples. I use the dialog all the time.
You can view their source and here is an example of one.
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Dialog - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#dialog" ).dialog();
});
</script>
</head>
<body>
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
</body>
You are able to customize this anyway you want. The link will show you how to do this.
EDIT: Since you want to open it in the behind code, I'll show you my jQuery and how I call it in the behind code. I use this to send emails.
function sendEmail() {
$("#email").dialog({
modal: true,
width: 700,
buttons: {
"Send": function () {
var btn = document.getElementById("<%=lbSend.ClientID %>");
if (btn) btn.click();
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
);
jQuery("#email").parent().appendTo(jQuery("form:first"));
};
Then in the behind code.
protected void btnEmail_Click(object sender, EventArgs e)
{
//this calls the jQuery function.
Page.ClientScript.RegisterStartupScript(this.GetType(), "Call my function", "sendEmail();", true);
}
In my experience, it's usually a sign of a bad design if you want to open something on the client side from the server side code behind. Are you sure that's what you need?
But assuming you do, you can use the ModalPopupExtender from the Ajax Control Tookit. It can be opened from client or server side. Here's a sample:
<ajaxToolkit:ModalPopupExtender ID="MPE" runat="server"
TargetControlID="LinkButton1" ClientIdMode="Static"
PopupControlID="Panel1" />
The PopupControlID should be the ID of a panel that you want to appear as a popup. You can put buttons on that panel if you need to. From the code behind, it's as simple as this...
MPE.Show();
To show it from JavaScript (assuming jQuery), make sure you set the ClientIdMode to Static, then call it...
$('#MPE').show();
public void Message(String msg)
{
string script = "window.onload = function(){ alert('";
script += msg;
script += "');";
script += "window.location = '";
script += "'; }";
ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);
}

prevent _doPostBack getting rendered in button markup

Is it possible to prevent the _doPostBack() call getting rendered on a button?
I would like add some custom logic prior to calling the postback.
I have added an onClick event to the button
e.g.
<button id="manualSubmit" runat="server" class="manual-submit" onclick="$('#jeweller-form').hide();" />
However, this just gets rendered inline before the _doPostBack()
But the postback gets fired before the jQueryHide takes place
I would like to call my own JS function then manually trigger the postback
any ideas?
Try this:
<button runat="server" id="Test" onserverclick="Test_ServerClick">Submit</button>
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var o = $("#Test"), c = o.attr("onclick");
o
.removeAttr("onclick")
.click(function(e) {
o.fadeOut("slow", function() {
o.fadeIn("slow", function() {
c(e);
});
});
return false;
});
});
</script>
Add return false; after the client-side code in the click event. In the HTMLControl, it didn't think it rendered __doPostBack; is the control that renders the _doPostBack, and the common way to prevent that for that control is:
<asp:Button ... OnClientClick="doThis();return false;" />
Which renders these JS statements before __doPostBack.
HTH.

Execute a javascript function when textbox is populated in jQuery?

How do I execute a function in JavaScript when a text box is populated with text? The text box with be hidden from the user. It will be populated by a USB magnetic card swiper.
Pseudo code:
<script language="javascript" type="text/javascript">
function MyFunction() {
//execute this function when MyTxtBox is populated
}
</script>
<asp:TextBox id="MyTxtBox" runat="server" Visible="false" />
Seems like you're doing this when the page loads. If you are, this would work.
$(document).ready(function(){
if($('#MyTxtBox').val().length > 0){
MyFunction();
}
});
If it's on change:
$(document).ready(function(){
$('#MyTxtBox').change(function(){
if($(this).val().length > 0){
MyFunction();
}
});
});
See munch's answer but use CSS to hide the text box as setting visible = false will result in the text box HTML not being rendered and therefore not being available on the client side.
<style type="text/css">
.USBBox
{
position: absolute;
left: -999em;
overflow: hidden;
}
</style>
<asp.textbox id="MyTextBox" runat="server" CSSClass="USBBox" />
You can then use jQuery's class selector to acces the text box and not worry about name mangling:
%('.USBBox')
If you have a lot of elements on the page however you might be better accessing by id, in which case use the client id to avoid any name mangling issues:
$('#<%= MyTextBox.ClientID %>')
Update
Used CSS solution provided in this link to hide the textbox from the user. Updated the USBBox CSS class with correct solution as setting display:none caused javaScript issues.
Attach to MyTxtBox's onChange event. You need to do a bit of ASP.NET to produce the appropriate ClientID for use in JavaScript, since ASP.NET will modify the MyTxtBox ID into something else.
<asp:TextBox id="MyTxtBox" runat="server" Visible="false" />
<script language="javascript" type="text/javascript">
function MyFunction() {
//execute this function when MyTxtBox is populated
}
document.getElementById("<%= MyTxtBox.ClientID %>").onChange = MyFunction;
</script>

Javascript to access control in MasterPage

I have a textbox control Super1 in my MasterPage.
I am using javascript to access this control from my content page like this:
<asp:Content ID="ContentPage" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script type="text/javascript">
function Somethin() {
{
document.forms[0].elements['Super1'].value = "sdfsd";
//document.getElementById('<%=Super1.ClientID%>').value = "sdfsdf";
}
}
</script>
</asp:Content>
But while page load it says Super1 not found. How can I access Super1?
In your masterpage's onload add this code :
string script = #"<script>
function Somethin() {
document.getElementById('" + Super1.ClientID + #"').value = 'sdfsd';
}
Somethin();
</script>";
if (!Page.ClientScript.IsClientScriptBlockRegistered("somethin_script_block"))
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "somethin_script_block", script);
}
this will add your script to the end of the page.
EDIT : I just realized, you use your controls ID directly in your javascript code. this may cause the exception. I update your code to fix it.
I hope this helps.
You have to make sure the document has loaded, make sure to call your functions that rely on the DOM being loaded onload. E.g.:
<script type="text/javascript">
window.onload = function() {
Somethin();
}
</script>
From the sample code you posted and since you said you are using a control, check the rendered id of the control you are trying to get at. In my experience the name is something crazy like ctl100_masterpagename_namingcontainer_controlname... that needs to show up in the js as well.
Super1 might be in a different naming container (the masterpage's control collection). You either need to render out the clientid of the control in a global javascript variable during the masterpage rendering so it can be accessed by javascript in the child page or you need to get a reference to the Masterpage, find the control there and write out the client Id in your child pages javascript...
Something like...
if the text box is in its own content place holder
var txtSuper1 = Master.FindControl("ContentPlaceHolderName").FindControl("Super1") as Textbox;
or if its not in a content place holder
var txtSuper1 = Master.FindControl("Super1") as Textbox;
3rd option might be to expose the control as a property of the masterpage (not sure) - my webforms is rusty.
On the master page, declare a javascript variable for the control, e.g:
<asp:TextBox id="Super1" runat="server"/>
...
<script type="text/javascript">
var txtSuper1 = document.getElementById('<%= Super1.ClientID %>');
</script>
It's important that you use the ClientID property, because the rendered control's ID (on the client) will be different from the server control's ID (due to naming containers).
Now you can access the textbox from javascript declared in the content pages:
<asp:Content ID="ContentPage" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script type="text/javascript">
function Somethin()
{
txtSuper1.value = "sdfsd";
}
</script>
click me
</asp:Content>
BTW: in your code there are duplicate curly-braces in function Somethin() {{ ... }}

How to use JQuery with Master Pages?

I can get simple examples to work fine as long as there's no master page involved. All I want to do is click a button and have it say "hello world" with the javascript in a .js file, using a master page. Any help very much appreciated :)
EDIT
As #Adam points out in the comments, there is a native jQuery mechanism that basically does the same thing as the hack in my original answer. Using jQuery you can do
$('[id$=myButton]').click(function(){ alert('button clicked'); });
My hack was originally developed as a Prototype work around for ASP.NET and I adapted it for the original answer. Note that jQuery basically does the same thing under the hood. I recommend using the jQuery way, though, over implementing my hack.
Original answer left for comment context
When you use a master page, ASP.NET mangles the names of the controls on the dependent pages. You'll need to figure out a way to find the right control to add the handler to (assuming you're adding the handler with javascript).
I use this function to do that:
function asp$( id, tagName ) {
var idRegexp = new RegExp( id + '$', 'i' );
var tags = new Array();
if (tagName) {
tags = document.getElementsByTagName( tagName );
}
else {
tags = document.getElementsByName( id );
}
var control = null;
for (var i = 0; i < tags.length; ++i) {
var ctl = tags[i];
if (idRegexp.test(ctl.id)) {
control = ctl;
break;
}
}
if (control) {
return $(control.id);
}
else {
return null;
}
}
Then you can do something like:
jQuery(asp$('myButton','input')).click ( function() { alert('button clicked'); } );
where you have the following on your child page
<asp:Button ID="myButton" runat="server" Text="Click Me" />
If your site has content pages in other folders, using the Page's ResolveUrl method in the src path will ensure that your js file can always be found:
<script type="text/javascript" src='<%= ResolveUrl("~/Scripts/jquery-1.2.6.min.js") %>' ></script>
Make sure that jQuery is being added in the master page. Given that you have this control:
<asp:Button ID="myButton" runat="server" Text="Submit" />
You can wireup the javascript with this:
$(document).ready(function() {
$('[id$=myButton]').click(function() { alert('button clicked'); });
});
$(document).ready() fires when the DOM is fully loaded, and all the elements should be there. You can simplify this further with
$(function() {});
The selector syntax $('[id$=myButton]') searches elements based on their id attribute, but matches only the end of the string. Conversely, '[id^=myButton]' would match the beginning, but for the purposes of filtering out the UniqueID that wouldn't be very useful. There are many many more useful selectors you can use with jQuery. Learn them all, and a lot of your work will be done for you.
The problem is that ASP.Net creates a unique id and name attribute for each element, which makes finding them difficult. It used to be that you'd need to pass the UniqueID property to the javascript from the server, but jQuery makes that unneccessary.
With the power of jQuery's selectors, you can decouple the javascript from the server-side altogether, and wireup events directly in your javascript code. You shouldn't have to add javascript into the markup anymore, which helps readability and makes refactoring much easier.
Just move the <script type="text/javascript" src="jquery.js" /> tag into the head tag in the master page. Then you can use jquery in all content pages.
There is no magic about using master pages with jQuery.
Adam's solution is the best. Simple!
Master page:
<head runat="server">
<title></title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
</head>
Content page:
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript">
$(document).ready(function () {
$("[id$=AlertButton]").click(function () {
alert("Welcome jQuery !");
});
});
</script>
</asp:Content>
where the button is
<asp:Button ID="AlertButton" runat="server" Text="Button" />
Reference the the Jquery .js file in the head of the MasterPage as follows:
<script type="text/javascript" src="/Scripts/jquery-1.2.6.min.js"></script>
(some browsers don't like ending it with />)
Then you can write things like
$('#<%= myBtn.ClientID%>').show()
in your javascript making sure to use the ClientId when referencing an ASP.Net control in your client code. That will handle any "mangling" of names and ids of the controls.
Master page:
The jQuery library goes in the master page. See if the path is correctly referenced. You might like to add the extra documentation like this:
<head>
<script type="text/javascript" src="/Scripts/jquery-1.2.6.min.js"></script>
<% if (false) { %>
<script type="text/javascript" src="/Scripts/jquery-1.2.6-vsdoc.js"></script>
<% } %>
</head>
Master page:
<head>
<script type="text/javascript">
$(document).ready(
function()
{
alert('Hello!');
}
);
</script>
</head>
CodeBehind for content pages and user controls:
this.textBox.Attributes.Add("onChange",
String.Format("passElementReferenceToJavascript({0})", this.textBox.ClientID));
Check out this post:
http://blogs.msdn.com/webdevtools/archive/2008/10/28/rich-intellisense-for-jquery.aspx
also explains how to get intellisense for jQuery in Visual studio.
When pages are rendered along with master pages, control id gets changed on page rendering so we can't refer them in jQuery like this #controlid. Instead we should try using input[id$=controlid]. If control is rendered as input control or if as anchor tag use a[id$=controlid] in jQuery.
In case if some one wants to access a label, here is the syntax
$('[id$=lbl]').text('Hello');
where lbl is the label id and the text to display in the label is 'Hello'
I also started with the simplest of examples and had no luck. I finally had to add the jquery .js file outside of the <head> section of the master page. It was the only way I could get anything to work in Firefox (haven't tried other browsers just yet).
I also had to reference the .js file with an absolute address. Not entirely sure what's up with that one.
Adam Lassek linked to using jQuery selectors, though I think its worth explicitly calling out selecting elements by their class, as opposed to their id.
e.g. Instead of $("#myButton").click(function() { alert('button clicked'); });
instead use $(".myButtonCssClass").click(function() { alert('button clicked'); });
and add the class to the button:
<asp:Button ID="myButton" runat="server" Text="Submit" CssClass="myButtonCssClass" />
This has the benefit of not having to worry about whether two control ids 'end' the same way in addition to being able to apply the same jQuery code to multiple controls at a time (with the same css class).
PROBLEM --> when using Site.Master pages the control id names (for ASP controls) get the ContentPlaceHolderID prefixed to them.
(Note this not a problem for non-asp controls as they don't get 'reinterpreted' - i.e. they just appear as written)
SOLUTIONS:
Simplest --> add ClientIDMode="Static" to the asp control definition (or set with properties) in aspx page
Alternatives include:
Hardcoding the ContentPlaceHolderID name in the js code e.g "#ContentPlaceHolder1_controlName" - eek!!!!
using the <%= controlName.ClientID %> in the ASP page - plus, assigning it - there- to a variable (or object of variables). The variable (or object dot notation) can then be used in external js page
(NOTE: Can't use <%= controlName.ClientID %> in external js)
Using CssClass with a unique(same name as ID) in ASP page and refering to the control as ".controlName" instead of "#controlName"
Using the "[id$=_controlName]" instead of "#controlName" - this is involves a small search and is looking for a control that ends with the unique name - that way the start is irrelevant

Resources