public partial class Test : Page { protected override void OnLoad(EventArgs e) { base.OnLoad(e); string[] months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; for (int y = 1998; y < 2010; y++) { this.Response.Write(y + " = "); foreach (string m in months) { this.Response.Write(m + ": " + Month.GetLastDate(m, y)); this.Response.Write(" - "); } this.Response.Write("<hr />"); } } protected override void OnInit(EventArgs e) { } } public class Month { public enum MonthEndDate { Jan = 31, Feb = 28, Mar = 31, Apr = 30, May = 31, Jun = 30, Jul = 31, Aug = 31, Sep = 30, Oct = 31, Nov = 30, Dec = 31 }; public static int GetLastDate(string month, int year) { MonthEndDate endDate = (MonthEndDate)Enum.Parse(typeof(MonthEndDate), month); int enddate = (int)endDate; if (endDate == MonthEndDate.Feb) if (year % 4 == 0) enddate++; return enddate; } }
Tuesday, June 29, 2010
How to find end date of any month in any year - C#
We can use an Enum to find end dates of any month in given year:
How to disable weekends of asp.net calender - Asp.net
We can use following properties to disable days of the asp.net calender.
- e.Cell.Enabled
- e.Day.IsSelectable
- e.Cell.BackColor
<html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> <script runat="server"> protected void DayRander(object sender, DayRenderEventArgs e) { if(e.Day.IsWeekend) { e.Cell.Enabled = false; e.Day.IsSelectable = false; e.Cell.BackColor = Color.Gray; } } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:Calendar runat="server" ID="calDates" OnDayRender="DayRander" /> </div> </form> </body> </html>
How to disable day of asp.net calender based on criteria - Asp.net
Inorder to disable perticular date in calender, we can use three properties of day render event arguement.
- e.Cell.Enabled
- e.Day.IsSelectable
- e.Cell.BackColor = Color.Gray
<html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> <script runat="server"> List<DateTime> validDays = new List<DateTime>(); protected override void OnLoad(EventArgs e) { validDays = this.FindValidDates(); } private List<DateTime> FindValidDates() { int month = DateTime.Now.Month; int year = DateTime.Now.Year; for (int i = 1; i < 31; i += 2) validDays.Add(new DateTime(year, month, i)); return validDays; } protected void DayRander(object sender, DayRenderEventArgs e) { if (!validDays.Exists(x => x == e.Day.Date)) { e.Cell.Enabled = false; e.Day.IsSelectable = false; e.Cell.BackColor = Color.Gray; } } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:Calendar runat="server" ID="calDates" OnDayRender="DayRander" /> </div> </form> </body> </html>
How to configure directory browsing - II6 / IIS7
How to set up direcotry browsing in IIS 7
1.Open IIS manager - run inetmgr
2.Expand the tree, under [Server Name]/Sites - Click on web site / virtual direcotry required
3.Under IIS section, please click on direcotry bowsing section.
4.On the righthand side please click on Enable/Disable directory browsing option.
How to setup direcotry browsing in IIS6
1.Open IIS manger - run inetmgr
2.Expand the tree, under [Server Name]/Web Sites - right click on web site / virtual directory required.
3.Under Home Directory please check/uncheck Directory Bowsing option
1.Open IIS manager - run inetmgr
2.Expand the tree, under [Server Name]/Sites - Click on web site / virtual direcotry required
3.Under IIS section, please click on direcotry bowsing section.
4.On the righthand side please click on Enable/Disable directory browsing option.
How to setup direcotry browsing in IIS6
1.Open IIS manger - run inetmgr
2.Expand the tree, under [Server Name]/Web Sites - right click on web site / virtual directory required.
3.Under Home Directory please check/uncheck Directory Bowsing option
Monday, June 28, 2010
How to show the progress of long running operation - Simple Example
Demo:
This article demonstrates how to show the progress of a long running operation using simple label text. But you can add a spning progress indicator and make it much fancy.
Screenshots:
Markup:
This article demonstrates how to show the progress of a long running operation using simple label text. But you can add a spning progress indicator and make it much fancy.
Screenshots:
Markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="ActiveTest.Test" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> <style type="text/css"> .Hide { display:none; } </style> </head> <body> <form id="form1" runat="server"> <div> <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"> </asp:ToolkitScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:Button runat="server" ID="btnDoTask" Text="Do Task" OnClick="Button1_Click" /> <asp:Label runat="server" ID="lblMessage" /> <asp:Button runat="server" ID="btnHidden" UseSubmitBehavior="false" CssClass="Hide" /> </ContentTemplate> </asp:UpdatePanel> </div> </form> </body> </html>Code behind:
public partial class Test : Page { private string script = @"setTimeout(""__doPostBack('{0}','')"", 5000);"; public bool Processing { get { return (bool)(Session["Processing"] ?? false); } set { Session["Processing"] = value; } } public bool Completed { get { return (bool)(Session["Completed"] ?? (Session["Completed"] = true)); } set { Session["Completed"] = value; } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (this.Processing) { this.lblMessage.Text = "Processing... Please wait..."; ScriptManager.RegisterStartupScript(this, this.GetType(), this.GetType().Name, string.Format(script, this.btnHidden.ClientID), true); } else { if (!this.Completed) { lblMessage.Text = "Processing is complete"; this.Completed = true; } else lblMessage.Text = string.Empty; } } protected void Button1_Click(object sender, EventArgs e) { Thread thread = new Thread(new ThreadStart(SomeLongOperation)); thread.Start(); this.lblMessage.Text = "Processing... Please wait..."; this.Processing = true; ScriptManager.RegisterStartupScript(this, this.GetType(), this.GetType().Name, string.Format(script, this.btnHidden.ClientID), true); } void SomeLongOperation() { this.Completed = false; for (int i = 0; i < 20; i++) Thread.Sleep(1000); this.Processing = false; } }
How to export html in to Microsoft Excel - Asp.net
This article demonstrate how to export html as Microsoft xl format
Response.ContentType = "application/force-download"; Response.AddHeader("content-disposition", "attachment; filename=Report.xls"); Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">"); Response.Write("<head>"); Response.Write("<META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"); Response.Write("<!--[if gte mso 9]><xml>"); Response.Write("<x:ExcelWorkbook>"); Response.Write("<x:ExcelWorksheets>"); Response.Write("<x:ExcelWorksheet>"); Response.Write("<x:Name>Report Data</x:Name>"); Response.Write("<x:WorksheetOptions>"); Response.Write("<x:Print>"); Response.Write("<x:ValidPrinterInfo/>"); Response.Write("</x:Print>"); Response.Write("</x:WorksheetOptions>"); Response.Write("</x:ExcelWorksheet>"); Response.Write("</x:ExcelWorksheets>"); Response.Write("</x:ExcelWorkbook>"); Response.Write("</xml>"); Response.Write("<![endif]--> "); Response.Write("</head>"); /// /// Assign your HTML content here /// Response.Write(output); Response.Flush();
Sunday, June 27, 2010
The Client Disconnected - Asp.net
You're likely to sporadically get this error message if you're in a web farm and you have a page where the user can make multiple selections, it typically happens in this scenario:
The user selects a drop downlist box that has an event on postback, but the user does this again before the request is sent back to the user, the user is now creating a second event that is being fired on the other webserver, the previous webserver tries to return the results of the old event to the user but the user is no longer there because the user is now on the other webserver.
The user will never see an error, but if your catching the errors and emailing/logging them you'll see them like shown below and be totally frustrated. Don't worry about it, just ignore it it's not even an problem, as long as you're trapping this kind of error nothing will go wrong.
Type : System.Web.HttpException, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a Message : The client disconnected. Source : System.Web Help link : ErrorCode : -2147467259 Data : System.Collections.ListDictionaryInternal TargetSite : Void ThrowError(System.Exception, System.String, System.String, Boolean) Stack Trace : at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) at System.Web.UI.HiddenFieldPageStatePersister.Load() at System.Web.UI.Page.LoadPageStateFromPersistenceMedium() at System.Web.UI.Page.LoadAllState() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.src_rptprefs_chainhierarchy_aspx.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
The user selects a drop downlist box that has an event on postback, but the user does this again before the request is sent back to the user, the user is now creating a second event that is being fired on the other webserver, the previous webserver tries to return the results of the old event to the user but the user is no longer there because the user is now on the other webserver.
The user will never see an error, but if your catching the errors and emailing/logging them you'll see them like shown below and be totally frustrated. Don't worry about it, just ignore it it's not even an problem, as long as you're trapping this kind of error nothing will go wrong.
Type : System.Web.HttpException, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a Message : The client disconnected. Source : System.Web Help link : ErrorCode : -2147467259 Data : System.Collections.ListDictionaryInternal TargetSite : Void ThrowError(System.Exception, System.String, System.String, Boolean) Stack Trace : at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) at System.Web.UI.HiddenFieldPageStatePersister.Load() at System.Web.UI.Page.LoadPageStateFromPersistenceMedium() at System.Web.UI.Page.LoadAllState() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.src_rptprefs_chainhierarchy_aspx.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Inner Exception
---------------
Type : System.Web.UI.ViewStateException, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
Message : Invalid viewstate.
Client IP: 10.21.4.8
Port: 46784
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; InfoPath.1;
Friday, June 25, 2010
How to mask credit card number using javascript - Asp.net Javascripts
<%@ Page Language="C#" %> <html> <head id="Head1" runat="server"> <script runat="server"> protected override void OnLoad(EventArgs e) { base.OnLoad(e); this.txtCreditCardNo.Attributes.Add("onkeyup", "javascript:Mask(this)"); } </script> <script language="javascript" type="text/javascript"> function Mask(obj, evt) { evt = (evt) ? evt : window.event var charCode = (evt.which) ? evt.which : evt.keyCode var txtValue = window.document.getElementById('txtCreditCardNo'); if ((charCode < 45 || charCode > 57) && charCode != 8 && charCode != 37 && charCode != 39) { alert("This field accepts numbers only"); txtValue.value = txtValue.value.substr(0, txtValue.value.length - 1); return false } else { var hdnValue = window.document.getElementById('hdnCreditCardNo'); if (charCode == 8) { if (hdnValue.value.length > txtValue.value.length) { hdnValue.value = hdnValue.value.substr(0, txtValue.value.length); } } else { hdnValue.value = hdnValue.value + String.fromCharCode(charCode); } } if (txtValue.value.length > 5) { txtValue.value = "*****" + txtValue.value.substr(5, txtValue.value.length); } else { var mask = ""; for (i = 0; i < txtValue.value.length; i++) mask += "*"; txtValue.value = mask; } return true } </script> </head> <body> <form id="form1" runat="server"> <asp:TextBox runat="server" ID="txtCreditCardNo" /> <asp:TextBox runat="server" ID="hdnCreditCardNo" Text="" /> </form> </body> </html>
Thursday, June 24, 2010
How to download a image using c# - Asp.net
Download a image we have to set file attachment and content type of the response.
Demo:
Example:
Demo:
Example:
public void DownloadPicture(object sender, EventArgs e) { ImageButton button = sender as ImageButton; if (button != null) { string fileName = button.CommandArgument; this.Response.AddHeader( "content-disposition", string.Format( "attachment;filename={0}", Path.GetFileName(fileName))); this.Response.ContentType = "image/jpg"; this.Response.WriteFile(this.Server.MapPath(fileName)); } }
How to dynamically add a row of controls using add button : Asp.net - Part 1: The Simple Version
Demo:
This example demonstrate how to add controls to asp.net page using add button using a hidden field. However because there is no viewsate present in the page init method, we have to use request form collection to access the row count
If you need a full version of this example including clearbutton and enter button key press to add new row, please see this artilce.
Ps: this is the basic version - full version is available here.
Example:
This example demonstrate how to add controls to asp.net page using add button using a hidden field. However because there is no viewsate present in the page init method, we have to use request form collection to access the row count
If you need a full version of this example including clearbutton and enter button key press to add new row, please see this artilce.
Ps: this is the basic version - full version is available here.
Example:
<%@ Page Language="C#"%> <html> <head id="Head1" runat="server"> <script runat="server"> int cols = 4; int numberOfRows = 0; public int NumberOfRows { get { return int.Parse(this.Request.Form[this.htnRowCount.UniqueID] ?? "1"); } set { this.htnRowCount.Value = value.ToString(); } } protected override void OnInit(EventArgs e) { base.OnInit(e); Table table = new Table(); string target = this.Request.Form.Get("__EVENTTARGET"); if (string.IsNullOrEmpty(target)) numberOfRows=1; else { if (target.Equals(this.btnAdd.UniqueID)) numberOfRows = this.NumberOfRows + 1; } for (int i = 0; i < numberOfRows; i++) { TableRow tr = new TableRow(); for (int j = 0; j < cols; j++) { TableCell td = new TableCell(); td.Controls.Add(new TextBox() { ID = "Cell" + i + j }); tr.Controls.Add(td); } table.Rows.Add(tr); } this.phCells.Controls.Add(table); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); this.NumberOfRows = numberOfRows; } </script> </head> <body> <form id="form1" runat="server"> <asp:PlaceHolder runat="server" ID="phCells"></asp:PlaceHolder> <asp:Button runat="server" ID="btnAdd" Text="Add" UseSubmitBehavior="false" /> <asp:HiddenField runat="server" ID="htnRowCount" Value="1" /> </form> </body> </html>
Wednesday, June 23, 2010
How to replace html content inside html using c# - Asp.net
This example demonstrate how to replace HTML element content (innerHtml) using c#. I have used regular expressions to match elements. However this example does not support nested eleements:
private string ReplaceElements(string html) { string patten = @"<\s*div[^>]*>(.*?)<\s*/div\s*>"; string wrapper = @"<div class=""Highlighter"">{0}</div>"; MatchCollection collection = Regex.Matches(html, patten); foreach (Match match in collection) { string value = match.Value; int marker = value.IndexOf(">"); string innterHtml = value.Substring(marker + 1, value.Length - (marker + 7)); if (Regex.Match(innterHtml, patten).Success) innterHtml = this.ReplaceElements(innterHtml); string wrappedText = string.Format(wrapper, innterHtml); string modifiedValue = value.Replace(innterHtml, wrappedText); html = html.Replace(value, modifiedValue); } return html; } protected override void Render(HtmlTextWriter writer) { string html = @" <html> <head> <title>Test Page</title> <style> div.Highlighter { border:solid 1px #f00; margin:10px; } </style> </head> <body> <div class=""Div""><p>Hello World</p></div> <div class=""Div"" runat=""server"">Div 1</div> <div class=""Div"" id=""LoginId"">Div 2</div> <div class=""Div"" width=""50%"">Div 3</div> <div class=""Div"">Div 4</div> </body> </html> "; writer.Write("<h1>Before</h1>"); writer.Write("<hr />"); writer.Write(html); writer.Write("<h1>After</h1>"); writer.Write("<hr />"); html = this.ReplaceElements(html); writer.Write(html); }
Tuesday, June 22, 2010
How to bubble up an event from usercontrol to parent page(control) (Part 1 - With Delegates)- Asp.net
This article demonstrate how to bubble up events from user-control to parent page or control. To bubble up event I use event and delegate.
UserControl : Code
Control : Markup
Consuming page:
Please note: If you add a event called ButtonClicked to the usercontrol, in the markup, .net convert it to OnButtonClicked.
UserControl : Code
public partial class ActiveUserControl : UserControl { public event EventHandler ButtonClicked; protected void InvokeButtonClicked(object sender, EventArgs e) { if (this.ButtonClicked != null) this.ButtonClicked(sender, e); } }
Control : Markup
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ActiveUserControl.ascx.cs" Inherits="ActiveTest.UserControls.ActiveUserControl" %> <asp:Button runat="server" ID="btnButton" Text="Button" OnClick="InvokeButtonClicked" />
Consuming page:
<%@ Page Language="C#" %> <%@ Register TagName="uc" TagPrefix="active" Src="~/UserControls/ActiveUserControl.ascx" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <script runat="server"> protected void ButtonClicked(object sender, EventArgs e) { /// /// Bubbled up event /// } </script> </head> <body> <form id="form1" runat="server"> <active:uc runat="server" ID="ucUserControl" OnButtonClicked="ButtonClicked" /> </form> </body> </html>
Monday, June 21, 2010
How to find Request date and time on a Postback - Asp.net
This article demonstrate how to find date and time of the client using javascript and hidden field. For the first page load it does not know the date and time but after that it hold the date and time of the client in the hidden field
<html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> <script runat="server"> protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (this.IsPostBack) { string strRequestTime = this.hdnTime.Value; DateTime requestTime = DateTime.Parse(strRequestTime); this.Response.Write("Request's Clents Time: " + requestTime.ToString()); } } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox runat="server" ID="txtPromoCode" /> <asp:Button runat="server" ID="btnPromotin" Text="Apply Promotion" /> <asp:HiddenField runat="server" ID="hdnTime" /> </div> </form> <script language="javascript" type="text/javascript"> var currentTime = new Date() var month = currentTime.getMonth() + 1; var day = currentTime.getDate(); var year = currentTime.getFullYear(); var hour = currentTime.getHours(); var minute = currentTime.getMinutes(); var second = currentTime.getSeconds(); var hdnTime = document.getElementById('<%= this.hdnTime.ClientID %>'); hdnTime.value = day + "/" + month + "/" + year + " " + hour + ":" + minute + ":" + second; </script> </body> </html>
Friday, June 18, 2010
How to find the control which caused a postback ( Part 2 : Inside the dedecated event handler) - Asp.net
This article demonstrate how to find the postback control inside the dedicated event handler. Simply we use command arguement propery of a button to after casting sender of the event to required type
<%@ Page Language="C#" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <script runat="server"> protected void LinkClicked(object sender, EventArgs e) { LinkButton linkButton = sender as LinkButton; if (linkButton != null) this.Response.Write(linkButton.CommandArgument); } </script> </head> <body> <form id="form1" runat="server"> <asp:LinkButton runat="server" ID="LinkButton1" CommandArgument="LinkButton1" OnClick="LinkClicked" Text="LinkButton 1" /> <asp:LinkButton runat="server" ID="LinkButton2" CommandArgument="LinkButton2" OnClick="LinkClicked" Text="LinkButton 2" /> <asp:LinkButton runat="server" ID="LinkButton3" CommandArgument="LinkButton3" OnClick="LinkClicked" Text="LinkButton 3" /> <asp:LinkButton runat="server" ID="LinkButton4" CommandArgument="LinkButton4" OnClick="LinkClicked" Text="LinkButton 4" /> <asp:LinkButton runat="server" ID="LinkButton5" CommandArgument="LinkButton5" OnClick="LinkClicked" Text="LinkButton 5" /> </form> </body> </html>
"Reduce repetitive work" [REDUCE RE-WORK] - Software Development And Asp.net
One critical issue might slow down software development process is repetitive work.
Where this happen:
Analysing: Understanding problem domain 100% and delivering the ideal solution to the client will be the ideal case. However in reality lack of understanding problem domain cause less achievement of client goals which can cause a re-work.
Agreements: Lack of understanding to end point and clear objectives, both developer and clients get confused causing clients to change their mind at the last minute which can cause re-work.
When you are coding: If we can write a programme like we write a love letter, it will be the ideal case. But this is not. But having a proper plan what you are going to implement you can write programmes. But in really we develop programmes. Development involves revisions and iteration and re-work.
How to minimise repetitive work:
Where this happen:
Analysing: Understanding problem domain 100% and delivering the ideal solution to the client will be the ideal case. However in reality lack of understanding problem domain cause less achievement of client goals which can cause a re-work.
Agreements: Lack of understanding to end point and clear objectives, both developer and clients get confused causing clients to change their mind at the last minute which can cause re-work.
When you are coding: If we can write a programme like we write a love letter, it will be the ideal case. But this is not. But having a proper plan what you are going to implement you can write programmes. But in really we develop programmes. Development involves revisions and iteration and re-work.
How to minimise repetitive work:
- Spend fair time of background study and understanding the problem. For example if you implement an accounting system, it is better to have some background knowledge of accounting.
- Produce mock-up as much as possible. Get mock-ups agreed by the client.
- Document requirements properly and re-wise and get sign off by the client.
- Provide a good architecture to the solution. Consider using multi-tier-architecture. Use object oriented programming concepts. Occupy common software patterns as much as possible like MVC and Active Records
- Document the plan. I know this is painful but this save time a lot. What I would do is at least implement high level ER-Diagram and Class Diagram.
- Avoid copy and paste. If you use a common mark-up in several places implement a user control. Even better, if little repetitive segments of code you can implement custom server controls.
- Use asp.net master pages and asp.net themes and skins.
Thursday, June 17, 2010
How to access Page Method using Script Manager - Asp.net
Demo:
Using asp.net ScriptManger setting EnablePageMethods=true we can access WebMethods
Using asp.net ScriptManger setting EnablePageMethods=true we can access WebMethods
- Method should be static
- Set ScriptManager EnablePageMethods=true
- Use java script PageMethods.CheckUserName(value, OnSucceeded, OnFailed);
- OnSucceeded - function to executed on success
- OnFailed - function to executed on fail
<%@ Page Language="C#" %> <html> <head id="Head1" runat="server"> <title></title> <script runat="server"> [System.Web.Services.WebMethod] public static string CheckUserName(string struname) { string uerror = string.Empty; try { bool userExists = false; /// /// Check if user exists /// if (struname.ToLower().Equals("bob")) userExists = true; if (userExists) uerror = "UserName already exists!"; else uerror = "UserName available!"; } catch { uerror = "Error"; } return uerror; } </script> <script type="text/javascript"> function checkUsername(soruce) { var valueuseremail = soruce.value; if (valueuseremail != "") { PageMethods.CheckUserName(valueuseremail, OnSucceeded, OnFailed); } } function OnSucceeded(result, usercontext, methodName) { document.getElementById('<%= lblValidationResult.ClientID %>').innerHTML = result; } function OnFailed(error, userContext, methodName) { alert("Error"); } </script> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager" runat="server" EnablePageMethods="true" /> <asp:TextBox ID="txtEmail" runat="server" onkeyup="checkUsername(this);"> </asp:TextBox> <asp:Label ID="lblValidationResult" runat="server"> </asp:Label> </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...
-
Why we need asynchronous tasks? Execute a time consuming operations in parallel to the CLR thread which execute the request If you have ...
-
Demo: I was thinking a way to show images before actually uploading them to server. I would say to preview images using javascript. Obv...