<%@ Page Language="C#" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <script language="javascript" type="text/javascript"> function checkIt(obj, evt) { evt = (evt) ? evt : window.event var charCode = (evt.which) ? evt.which : evt.keyCode if ((charCode < 45 || charCode > 57) && charCode != 8 && charCode != 37 && charCode != 39) { alert("This field accepts numbers only") return false } var t = (charCode / 1) - 48; var v = obj.value + t; var value = v / 1; if(value > 24){ alert("Number should be less than 24"); return false; } return true } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox runat="server" ID="txtNumber" onKeyPress='javascript:return checkIt(this, event)' /> </div> </form> </body> </html>
Showing posts with label JavaScripts. Show all posts
Showing posts with label JavaScripts. Show all posts
Saturday, December 17, 2011
How to validate a number between 0-24 with Java Scripts
Sunday, October 17, 2010
How to show budy cursor while processing a request
Please note this example deos not work in Mozilla Firefox.
Demo:
<%@ Page Language="C#" %> <html> <head id="Head1" runat="server"> <script runat="server"> public void Save(object sender, EventArgs e) { System.Threading.Thread.Sleep(5000); this.lblLastUpdate.Text = DateTime.Now.ToString("hh:mm:ss"); } </script> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager runat="server" ID="pageScriptManager"> </asp:ScriptManager> <script language="javascript" type="text/jscript"> Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () { document.body.style.cursor = "auto"; }); Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(function () { document.body.style.cursor = "wait"; }); </script> <asp:UpdatePanel runat="server" ID="upnlInsertContent"> <ContentTemplate> <asp:Button runat="server" ID="btnSave" OnClick="Save" Text="Save" /> <asp:Label runat="server" ID="lblLastUpdate" /> </ContentTemplate> </asp:UpdatePanel> </form> </body> </html>
Friday, October 01, 2010
How to show the progress of a request
Demo:
This approach is suitable if your request delays due to content downloading, such as images and other body content. Page response time cannot be predicted. For the first page load it gets all the data while subsequent responses get cached data. So if you provide constant delay on progress users may lose the joy or browser cache and improved performance by modern browsers. On the other hand, if your request gets delayed by execution of the page such as database calls, web service calls etc, you may consider handing long running operations.
- Simple example - only strat message and end message
- Detailed example - including progress bar and step processing results
- At the end of the page, we have the JavaScript to hide the progress bar.
- However, if you hide the progress bar immediately, user still notify a blank space.
- So if you certain that page loading take a while about 2-4 seconds it is better you delay the hide statement at the end of the page.
setTimeout("document.getElementById('progress').style.display = 'none'", 5000); Example: <%@ Page Language="C#" %> <html> <head runat="server"> <style type="text/css"> div.DialogueBackground { position:absolute; width:100%; height:100%; top:0; left:0; text-align:center; } div.DialogueBackground div.Dialogue { width:300px; height:100px; position:absolute; left:50%; top:50%; margin-left:-150px; margin-top:-50px; border:solid 10px #555; background-color:#fff; } div.DialogueBackground div.Dialogue p { padding:20px 10px; } </style> <script runat="server"> protected override void OnLoad(EventArgs e) { base.OnLoad(e); /// /// one MB size of request and resposne. /// for (int i = 0; i < 1000; i++) { Image img = new Image() { ImageUrl = "SomeImage" + i + ".png" }; img.Attributes.Add("style", "display:none"); this.phContent.Controls.Add(img); } } </script> </head> <body> <form id="form1" runat="server"> <div class="DialogueBackground" id="progress"> <div class="Dialogue"> <p>Please wait...</p> <img src="::root/::images/Progress.gif" alt="Processing" /> </div> </div> <asp:Button runat="server" ID="btnSave" Text="Save" OnClientClick="javascript:document.getElementById('progress').style.display = 'block'" /> <asp:PlaceHolder runat="server" ID="phContent" /> </form> <script language="javascript" type="text/javascript"> setTimeout("document.getElementById('progress').style.display = 'none'", 5000); </script> </body> </html>
Thursday, September 30, 2010
How to build an addable DropDownList (can add items using JavaScript )
Demo:
Sometimes asp.net developers find when they change the items collection in a DropDownList in the client side using JavaScripts in the very next postback they run in to Event Validation error. Yes, this is true, because any attacker can inject malicious items to the item list rather than the proper rendered list, they can break down your site. But the problem is there are some legitimate instances where we intentionally add items the DropDownList in the client side using JavaScripts.
This article provides a solution to add items at the client side without Event Validation errors. Idea is the handle item list in hidden field and mark the hidden field as the actual control. So in a postback, actually item list will not get validated but the hidden field get validated.
No problem so far, but how we can merge newly added items with excising items? For this, by the time I render the control, I add comma separated list of items as the value of hidden field. Then on the event of adding new items to the list in the client side, inside the JavaScript it appends the newly added items to the hidden field value. So job is almost done, then what we all need to do is, get the hidden field value in the LoadPostBackData event and repopulate the item list. Vola job done.
Control itself it renders the item adding JavaScript event (ready made) so all you need to do is call the JavaScript function with three parameters
Param1 - value of new item
Param2 - text of new item
Param3 - id of the DropDownList - ClientID
AddListItem(value, text, targetListId);
Markup:
<%@ Register Assembly="ActiveTest" Namespace="ActiveTest" TagPrefix="asp" %> <%@ Page Language="C#" %> <html> <head runat="server"> <script language="javascript" type="text/javascript"> function AddItem() { var value = document.getElementById('<%=txtValue.ClientID %>').value; var text = document.getElementById('<%=txtText.ClientID %>').value; var targetListId = '<%=addlFreeDownDownList.ClientID %>'; AddListItem(value, text, targetListId);
return false;
} </script> </head> <body> <form id="form1" runat="server"> Add Item - Text: <asp:TextBox runat="server" ID="txtText" /> Value: <asp:TextBox runat="server" ID="txtValue" /> <asp:Button runat="server" ID="btnAdd" Text="Add" OnClientClick="javascript:return AddItem()" /> <hr /> <asp:AddableDropDownList runat="server" ID="addlFreeDownDownList"> <asp:ListItem>Orange</asp:ListItem> <asp:ListItem>Blue</asp:ListItem> <asp:ListItem>Red</asp:ListItem> <asp:ListItem>Yellow</asp:ListItem> <asp:ListItem>Black</asp:ListItem> </asp:AddableDropDownList> <hr /> <asp:Button runat="server" ID="btnSave" Text="Save" /> </form> </body> </html>
Control:
public class AddableDropDownList : DropDownList { private string script = @" function AddListItem(value, text, target) { var list = target + ""List""; var option = document.createElement(""option""); document.getElementById(list).options.add(option); option.text = text; option.value = value; var target = document.getElementById(target); if (target.value == """") target.value = value + ""=="" + text; else target.value = target.value + "",:,"" + value + ""=="" + text; return false; } "; public string ListID { get { return this.ClientID + "List"; } } protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection) { string items = postCollection[postDataKey]; this.Items.Clear(); if (string.IsNullOrEmpty(items)) return true; foreach (string item in Regex.Split(items, ",:,")) { string[] s = Regex.Split(item, "=="); if (s.Length != 2) throw new Exception("Invalid item the list, list item cannot have == or ,:, combinations"); this.Items.Add(new ListItem(s[1], s[0])); } this.SelectedValue = postCollection[postDataKey + "List"]; return true; } protected override void Render(HtmlTextWriter writer) { StringBuilder content = new StringBuilder(); if (this.AutoPostBack) { StringBuilder script = new StringBuilder(this.Attributes["onchange"]); if (script.Length == 0) script.AppendFormat("javascript:{0}", string.Format("__doPostBack('{0}','');", this.ClientID)); else { if (!script.ToString().EndsWith(";")) script.Append(";"); script.AppendFormat("__doPostBack('{0}','');", this.ClientID); } this.Attributes.Add("onchange", script.ToString()); } StringBuilder b = new StringBuilder(); HtmlTextWriter h = new HtmlTextWriter(new StringWriter(b)); this.Attributes.Render(h); content.AppendFormat("<select id=\"{0}List\" name=\"{1}List\"{2}{3}>", this.ClientID, this.UniqueID, b.Length == 0 ? string.Empty : string.Format(" {0}", b.ToString()), !string.IsNullOrEmpty(this.CssClass) ? string.Format(" class=\"{0}\"", this.CssClass) : string.Empty); foreach (ListItem item in this.Items) content.AppendFormat("<option value=\"{0}\"{1}>{2}</option>", item.Value, item.Selected ? " selected=\"selected\"" : string.Empty, item.Text); content.Append("</select>"); content.AppendFormat("<input type=\"hidden\" id=\"{0}\" name=\"{1}\" value=\"{2}\" />", this.ClientID, this.UniqueID, this.GetValue()); writer.Write(content.ToString()); } private string GetValue() { StringBuilder value = new StringBuilder(); foreach (ListItem item in this.Items) { if (value.Length != 0) value.Append(",:,"); value.AppendFormat("{0}=={1}", item.Value, item.Text); } return value.ToString(); } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), this.GetType().Name, this.script, true); } }
Wednesday, September 29, 2010
How to show the progress of long running operation
- Simple example - only strat message and end message
- Detailed example - including progress bar and step processing results
- How to show the progress of a request - using JavaScripts and CSS
Wednesday, September 15, 2010
How to register User Control specific CSS and Java Scripts
It is always optimistic to include usercontrol specific CSS and JS files only when the UserControl renders it's contents.
CSS File:
I have CSS and JS files in the root of my web projects. If you would like to put then in diffrent folders you should specify the correct path along with the root url.
Then you can use Literral control to register the css and the ClientScript to register the JS files.
CSS File:
#userControlWrapper { width:400px; height:400px; border:solid 1px #f00; background-color:#aaa; } h1.Big { font-size:40px; }Markup:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl.ascx.cs" Inherits="ActiveTest.WebUserControl" %> <div id="userControlWrapper"> <h1 class="Big">User Control...</h1> </div>
I have CSS and JS files in the root of my web projects. If you would like to put then in diffrent folders you should specify the correct path along with the root url.
Then you can use Literral control to register the css and the ClientScript to register the JS files.
namespace ActiveTest { public partial class WebUserControl : UserControl { public string RootUrl { get { Uri requestUri = Context.Request.Url; HttpRequest request = Context.Request; string rootUrl = string.Format("{0}{1}{2}{3}{4}", requestUri.Scheme, Uri.SchemeDelimiter, requestUri.Host, requestUri.IsDefaultPort ? string.Empty : string.Format(":{0}", requestUri.Port), request.ApplicationPath); return rootUrl.EndsWith("/") ? rootUrl : string.Format("{0}/", rootUrl); } } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); string styles = "<link href=\"{0}WebUserControl.css\" rel=\"stylesheet\" type=\"text/css\" />"; this.Page.Header.Controls.Add(new Literal() { Text = string.Format(styles, this.RootUrl) }); this.Page.ClientScript.RegisterClientScriptInclude(this.GetType().Name, string.Concat(this.RootUrl, "WebUserControl.js")); } } }
Monday, September 13, 2010
How to create a popup window on the fly using java script in c# code behind
<html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head2" runat="server"> <title>Test Page</title> <script runat="server"> private string script = @" var popup = window.open('','', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no'); popup.document.write(""{0}""); "; private StringBuilder body = new StringBuilder(); protected override void OnLoad(EventArgs e) { base.OnLoad(e); /// /// build your html document here /// body.Append("<html>"); body.Append("<head></head>"); body.Append("<body>"); body.Append("<h1>Hello World</h1>"); body.Append("<p>This is a popup window created on the fly"); body.Append("</body>"); } protected void OpenWindow(object sender, EventArgs e) { /// /// Check your condition /// bool myCondition = true; if (myCondition) { this.ClientScript.RegisterClientScriptBlock( this.GetType(), this.GetType().Name, string.Format(this.script, this.body.ToString()), true); } } </script> </head> <body> <form id="form2" runat="server"> <asp:LinkButton runat="server" ID="lnkButton" OnClick="OpenWindow" Text="Open a Window" /> </form> </body> </html>
Saturday, September 04, 2010
How to use ICallbackEventHandler and execute a server method from java script in Asp.net
Markup:
Reference - MSDN
<%@ Page Language="C#" CodeBehind="~/Test.aspx.cs" Inherits="ActiveTest.Test" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>ClientScriptManager Example</title> <script type="text/javascript"> var value1 = 0; var value2 = 0; function ReceiveServerData2(arg, context) { Message2.innerText = arg; value2 = arg; } function ProcessCallBackError(arg, context) { Message2.innerText = 'An error has occurred.'; } </script> </head> <body> <form id="Form1" runat="server"> <div> Callback 1 result: <span id="Message1">0</span> <br /> Callback 2 result: <span id="Message2">0</span> <br /> <br /> <input type="button" value="ClientCallBack1" onclick="CallTheServer1(value1, alert('Increment value'))" /> <input type="button" value="ClientCallBack2" onclick="CallTheServer2(value2, alert('Increment value'))" /> <br /> <br /> <asp:Label ID="lblMessage" runat="server"></asp:Label> </div> </form> </body> </html>Code Behind:
namespace ActiveTest { public partial class Test : Page, ICallbackEventHandler { #region Attributes public int callBackCount = 0; private string script = @" function ReceiveServerData1(arg, context) { Message1.innerText = arg; value1 = arg; } "; #endregion #region ICallbackEventHandler Members public void RaiseCallbackEvent(String eventArgument) { callBackCount = Convert.ToInt32(eventArgument) + 1; } public string GetCallbackResult() { return callBackCount.ToString(); } #endregion protected void Page_Load(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); sb.Append("No page postbacks have occurred."); if (Page.IsPostBack) { sb.Append("A page postback has occurred."); } this.lblMessage.Text = sb.ToString(); ClientScriptManager cs = Page.ClientScript; String cbReference1 = cs.GetCallbackEventReference(this, "arg", "ReceiveServerData1", this.script); String cbReference2 = cs.GetCallbackEventReference("'" + Page.UniqueID + "'", "arg", "ReceiveServerData2", "", "ProcessCallBackError", false); String callbackScript1 = "function CallTheServer1(arg, context) {" + cbReference1 + "; }"; String callbackScript2 = "function CallTheServer2(arg, context) {" + cbReference2 + "; }"; cs.RegisterClientScriptBlock(this.GetType(), "CallTheServer1", callbackScript1, true); cs.RegisterClientScriptBlock(this.GetType(), "CallTheServer2", callbackScript2, true); } } }
Reference - MSDN
Sunday, August 29, 2010
How to remove asp.net menu item using java script and jQuery
<%@ Page Language="C#" %> <html> <head id="Head1" runat="server"> <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script language="javascript"> $(document).ready(function () { $(".Hide").parent().remove(); }); </script> </head> <body> <form id="form1" runat="server"> <div class="Container"> <asp:SiteMapDataSource runat="server" ID="smdDataSource" ShowStartingNode="false" /> <asp:Menu runat="server" ID="menuItems" DataSourceID="smdDataSource"> <DynamicItemTemplate> <asp:HyperLink runat="server" ID="menuLink" Text='<%# Eval("Text") %>' NavigateUrl='<%# Eval("NavigateUrl") %>' CssClass='<%# (Eval("NavigateUrl").ToString()).Contains("HiddenPage.aspx")? "Hide" : "Normal" %>' /> </DynamicItemTemplate> </asp:Menu> </div> </form> </body> </html>
Wednesday, August 25, 2010
How to access values of server controls in client side
‘How to access values of server controls in client side’ is a frequently asked question in asp.net developer community. Technically solution to the question can be sub divided in to two simple answers.
1. How to access server control value in Page
We can use
var input = document.getElementById('<%=txtValue1.ClientID %>');Syntax to access server side controls in the client side. However
Please refer this article for more information
2. How to access server control values in UserControl or WebControl
In this case we have to hold the script in a string variable and inject necessary ClientIDs in the run time. Then use this.Page.RegisterClientScriptBlock(...) method to register the script by the render time.
this.Page.ClientScript.RegisterClientScriptBlock( this.GetType(), this.GetType().Name, string.Format(this.script, this.txtValue1.ClientID, this.txtValue2.ClientID, this.txtValue3.ClientID), true);Please refer this article for more information
How to access server side control values using java script and change in the client side - Part 1 [in a Page]
We can use ClientID propery of any control to access values of controls in the client side java scripts.
Example
var input = document.getElementById('<%=txtName.ClientID %>');
Example
<%@ Page Language="C#" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <script language="javascript"> function GetValue() { var input = document.getElementById('<%=txtValue1.ClientID %>'); alert(input.value); return false; } function SetValue() { var value = prompt("Input Value", "BMW"); var input = document.getElementById('<%=txtValue2.ClientID %>'); input.value = value; return false; } function TransferValue() { var input1 = document.getElementById('<%=txtValue1.ClientID %>'); var input3 = document.getElementById('<%=txtValue3.ClientID %>'); input3.value = input1.value; return false; } </script> </head> <body> <form id="form1" runat="server"> <h4>Get Value</h4> <asp:TextBox runat="server" ID="txtValue1" Text="Toyota" /> <asp:Button runat="server" ID="btnGetValue" Text="Get Value" OnClientClick="javascript:return GetValue()" /> <hr /> <h4>Set Value</h4> <asp:TextBox runat="server" ID="txtValue2" /> <asp:Button runat="server" ID="btnSetvalue" Text="Set Value" OnClientClick="javascript:return SetValue()" /> <hr /> <h4>Transfer Value</h4> <asp:TextBox runat="server" ID="txtValue3" /> <asp:Button runat="server" ID="btnTransferValue" Text="Transfer Value" OnClientClick="javascript:return TransferValue()" /> </form> </body> </html>
Subscribe to:
Posts (Atom)
Azure Storage Account Types
Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...
-
Demo: I was thinking a way to show images before actually uploading them to server. I would say to preview images using javascript. Obv...
-
Demo : I am using asp.net UpdatePanel control to partial page update. As there is no keyup event for the asp.net TextBox control, I add an ...