About the author

Vijay Kodali
E-mail me Send mail

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2024

Auto save Asp.net form values Asynchronously

In this article, I will explain how to save Asp.Net page values asynchronously (aka Gmail style of saving mail drafts).  

Introduction:

In the past, Web applications were known for having less usable, less responsive user interfaces. AJAX changed all of that. The application can work asynchronously and the user doesn't have to sit and wait for pages to refresh. :

What is Ajax?

Ajax (Asynchronous JavaScript and XML) is an approach to web development that uses client-side scripting to exchange data with a web server. 

Solution:

There are several ways of achieve it. In this article I am using AJAX functionality to call ASP.NET Web services from the browser by using client script. Yes, no updatepanel.  

Start by adding a web service to the project as shown below, name it as AsynchronousSave.asmx. Make this web service accessible from Script, by setting class qualified with the ScriptServiceAttribute attribute...  

[System.Web.Script.Services.ScriptService]    
public class AsynchronousSave : System.Web.Services.WebService 


Here is the AsynchronousSave webservice class: 
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class WebService2 : System.Web.Services.WebService
{

    [WebMethod]
    public string HelloWorld()
    {

        return "Hello World";

    }

    [WebMethod]
    public string SaveInput(String input)
    {
        string StrInput = Server.HtmlEncode(input); if (!String.IsNullOrEmpty(StrInput))
        {

            string[] strFields = StrInput.Split('+');

            //code to save all input values
            // you can easily savethese values to temp DB table, temp file or xml file
            //Dispaly last saved values

            return String.Format("Last saved text: FirstName {0} ,<br/> Last name {1} <br/> Last "

            + "saved draft {2} at {3}.", strFields[0], strFields[1], strFields[2], DateTime.Now);

        }

        else
        {

            return ""; //if input values are empty..retrun empty string
        }
    }
}
 
Nothing fancy here, just methods marked with [WebMethod] attribute. The Saveinput method takes an input string with “+” as delimiter between form values.  

To enable web service to be called from client side, add script manager to page  

<asp:ScriptManager runat="server" ID="scriptManager">
    <Services>
        <asp:ServiceReference Path="~/AsynchronousSave.asmx" />
    </Services>
</asp:ScriptManager>


And here is HTML of page

<div>
    First Name:<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox></br> 
    LastName:<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox></br> 
    Draft :<asp:TextBox ID="txtDraft" runat="server"></asp:TextBox></br></div>
<div id="Preview">

The following example shows the java script that makes service calls

<script language ="javascript" >
    //This function calls the web service    
    function SaveUserInput() {
        var fName = document.getElementById("txtFirstName");
        var lName = document.getElementById("txtLastName");
        var draft = document.getElementById("txtDraft");
        //Saving all input in a single value         
        var input = fName.value + "+" + lName.value + "+" + draft.value;
        //ProjName.WebServiceName.WebMethod         
        SampleApplication1.AsynchronousSave.SaveInput(input, SucceededCallback);
    }
    // This is the callback function that processes the Web Service return value.     
    function SucceededCallback(result) {
        var divPreview = document.getElementById("Preview");
        divPreview.innerHTML = result;
    }
    // execute SaveUserInput for every 10 sec, timeout value is in miliseconds
    window.setInterval('SaveUserInput()', 10000); 
    
</script>

Reference:

http://msdn.microsoft.com/en-us/library/bb398998.aspx

         


Tags:
Posted by vijay on Monday, November 23, 2009 2:17 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Disable Backspace to Previous Page in Asp.Net

The following code will allow backspace in textbox not on form. This code works perfectly in IE7/8,FireFox,Chrome

<script language=javascript>   
            
    function cancelBack()   
    {   
        if ((event.keyCode == 8 ||    
           (event.keyCode == 37 && event.altKey) ||    
           (event.keyCode == 39 && event.altKey))   
            &&    
           (event.srcElement.form == null || event.srcElement.isTextEdit == false)   
          )   
        {   
            event.cancelBubble = true;   
            event.returnValue = false;   
        }   
    }   
  
</script>   
<body onkeydown=cancelBack()>   

Tags:
Categories: ASP.Net 3.5 | JavaScript
Posted by vijay on Tuesday, September 2, 2008 9:50 AM
Permalink | Comments (6) | Post RSSRSS comment feed

Formatted Date based on the browser language setting

One of new feature that was added in Asp.net 3.5  is script globalization and localization. We can display date based on language setting of browser. Here is code snippet of displaying date in local language using script..

[code:c#]

   <script type="text/javascript">
        function formatDate() {
            var d = new Date();
            try {
                $get('Label1').innerHTML = d.localeFormat("dddd, dd MMMM yyyy HH:mm:ss");
            }
            catch (e) {
                alert("Error:" + e.message);
            }
        }
        window.onload
        {
            formatDate();
        }
    </script>

[/code]


Posted by vijay on Saturday, August 16, 2008 7:31 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Removing empty spaces and HTML tags from TextBox text on client side

Here is a small code to remove spaces from textbox's text in onblur event.

 

<asp:TextBox ID="TextBox2" runat="server" onblur="javascript:value=value.replace(/\s/g,'');"></asp:TextBox>

 

To remove HTML tags..

<asp:textbox id="TextBox2" runat="server" onblur="this.value = this.value.replace(/<\/?[^>]+>/gi, '');">
</asp:textbox>

 

Please let me know, if you have any issues.


Tags:
Posted by vijay on Thursday, June 12, 2008 1:24 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Change back ground color of Asp.net Textbox on validation failure

Here is a way of changing back ground color for Textbox on validation failure. The key here is using Page_ClientValidate function in javascript.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter a value"
    ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="btnClick();"
    OnClick="Button1_Click1" />

<script type="text/javascript"> 

    function btnClick() 
    { 
        if (!Page_ClientValidate()) 
        { 
            document.getElementById("TextBox1").style.backgroundColor="red"; 
        } 
    } 

    function ClearBackGround() 
    { 
        document.getElementById("TextBox1").style.backgroundColor=""; 
    } 

</script>
In Code behind

TextBox1.Attributes.Add("onkeypress", "ClearBackGround()");


Tags:
Categories: ASP.NET | JavaScript
Posted by vijay on Thursday, June 5, 2008 9:08 AM
Permalink | Comments (1) | Post RSSRSS comment feed

Detecting Asp.Net page close event

Sometimes we have to capture page close event or navigation event to alert users. For example, Alerting user for navigating away from input page without saving it. Check this java script code..

window.onbeforeunload= function(){
if((window.event.clientX<0) || (window.event.clientY<0))
    {
      event.returnValue = "Are you sure you want to navigate away from this page? You haven't saved this form.";
    }
};

This code works only in Ie6/7. And also keep in mind, we can never catch the browser close event for 100%. For example, what if the user kills the browser process or shut down OS.


Tags:
Posted by vijay on Thursday, March 20, 2008 2:49 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Add, Delete Items in DropDownList, ListBox using Javascript

I have seen lots of questions in Asp.Net forums for adding/deleting items in drop down list or list box using JavaScript. Here is the code...

<asp:DropDownList ID="DropDownList1" runat="server" Width="182px"> 
<asp:ListItem value="1" Text ="Approve"></asp:ListItem> 
<asp:ListItem value="2" Text ="Accept"></asp:ListItem> 
<asp:ListItem value="3" Text ="Test1"></asp:ListItem> 
<asp:ListItem value="4" Text ="Test2"></asp:ListItem> 
</asp:DropDownList> 

<input type="button" value="Remove selected item" onclick="JavaScript: DeleteItem();" /> 
<input type="text" id="ddlText" name="ddlText" /> 
<input type="text" id="ddlValue" name="ddlValue" /> 
<input type="button" value="Add item" onclick="JavaScript: AddItem();" /> 
<input type="hidden" id="ddlElements" name="ddlElements" runat="server" /> 
<asp:Button ID="Button1" runat="server" Text="Button" />
    <script type="text/javascript"> 
    function DeleteItem() 
    { 

        var dropDownListRef = document.getElementById('<%= DropDownList1.ClientID %>'); 
        var optionsList = ''; 

        if ( dropDownListRef.value.length > 0 ) 
        { 
            var itemIndex = dropDownListRef.selectedIndex;
       if ( itemIndex >= 0 ) 
            dropDownListRef.remove(itemIndex); 
        } 
        else 
        { 
            alert('Please select an item'); 
            dropDownListRef.focus(); 
            dropDownListRef.select(); 
        } 
          

        for (var i=0; i<dropDownListRef.options.length; i++) 
        { 
        var optionText = dropDownListRef.options[i].text;
        var optionValue = dropDownListRef.options[i].value; 
     
        if ( optionsList.length > 0 )
            optionsList += ';'; 
            optionsList += optionText; 
            optionsList += ';'; 
            optionsList += optionValue; 
        } 
        document.getElementById('<%= ddlElements.ClientID %>').value = optionsList; 
    } 


    function AddItem() 
    { 

        var dropDownListRef = document.getElementById('<%= DropDownList1.ClientID %>'); 
        var ddlTextRef = document.getElementById('ddlText'); 
        var ddlValueRef = document.getElementById('ddlValue'); 
        var optionsList = ''; 

        if ( ddlTextRef.value !="" && ddlValueRef.value!="" ) 
        { 
            var option1 = document.createElement("option"); 
            option1.text= ddlValueRef.value; 
            option1.value= ddlTextRef.value ; 
            dropDownListRef.options.add(option1); 
        } 
        else 
            alert('Please enter values'); 
          
        for (var i=0; i<dropDownListRef.options.length; i++) 
        { 

        var optionText = dropDownListRef.options[i].text;
        var optionValue = dropDownListRef.options[i].value; 
          
        if ( optionsList.length > 0 )
        
            optionsList += ';'; 
            optionsList += optionText; 
            optionsList += ';'; 
            optionsList += optionValue; 
        } 
            document.getElementById('<%= ddlElements.ClientID %>').value = optionsList; 
       
    } 

</script>

In Code behind Page_Load, add following code..

if (IsPostBack)
{
    DropDownList1.Items.Clear();
    string[] DropDownListArray = ddlElements.Value.Trim().Split(';'); 
    
    for (int i = 0; i < DropDownListArray.Length; i = i + 2)
    {
        string itemText = DropDownListArray[i];
        string itemValue = DropDownListArray[i + 1]; 
        DropDownList1.Items.Add(new ListItem(itemText, itemValue));
    }

}

string optionsList = string.Empty; 
for (int i = 0; i < DropDownList1.Items.Count; i++)
{
   string optionText = DropDownList1.Items[i].Text;
   string optionValue = DropDownList1.Items[i].Value;
          
    if (optionsList.Length > 0) 
      
    optionsList += ";";
    optionsList += optionText;
    optionsList += ';';
    optionsList += optionValue;
}

ddlElements.Value = optionsList; 

Update:  Client-side changes to a DropDownList/ListBox are not persisted server-side, so any changes made will be lost if a PostBack occurs. Added server-side persistence to code. (Thanks to tip form NC01)

 


Tags:
Posted by vijay on Friday, December 14, 2007 9:40 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Java Script function to only allow integers in the textbox

Here is sample code for TextBox Validation to allow Numbers only.

[code:c#]

<script type = "text/javascript" language = "javascript">

function CheckTextBox(i)
{
    if(i.value.length>0)
    {
    i.value = i.value.replace(/[^\d]+/g, '');
    }
}

</Script>

[/code]

In Code behind add this function to "onkeyup" event for TextBox

[code:c#]

TextBox1.Attributes.Add("onkeypress", "CheckTextBox(this)");

[/code]


Posted by vijay on Wednesday, November 14, 2007 7:54 PM
Permalink | Comments (0) | Post RSSRSS comment feed