Wednesday, November 9, 2011

JavaScript for Asp.Net Developers

Introduction

JavaScript along with Asp.net helps u to build web applications which are robust and effective. In this article the most commonly used tasks which can be achieved in Asp.net by using JavaScript are discussed. The article describes the following content. JavaScript to perform validations, JavaScript client side API for Asp.net Server Controls, Call a JavaScript from code behind and Vice-Versa, Grid View alert for deleting, Pass the C# variables to JavaScript array, Pop-up in Grid View.

Perform Validations using Java script:

Validating the web forms is the most important and common task in developing the applications. Validating the page without allowing the user to post the page to server enhances the user experience. In this section we will see how to validate the web form by using client side java script. Access the asp.net Server Controls using Java script:
You can access the asp.net server controls by using the following script:
var employeeid = document.getElementById('<%= TextBox1.ClientID %>');

similarly you can access all other controls in the form.
Make textbox to accept only digits: The following function is used to make a text box to accept only digits.
function isNumberKey(evt) {
       
        if (charCode = evt.which) {
            charCode = evt.which;
        }
        else {
            charCode = evt.keyCode;
        }
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }
        else {
            return true;
        }
   }
Validate the emailid: Emaild can be validate by checking the position of ‘@’ and ‘.’ characters in the emailid as follows:
var atpos = emailid.value.indexOf("@");
var dotpos = emailid.value.lastIndexOf(".");

   if ((inputDOJ.value == "") || (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= inputDOJ.length)) 
    {
         lbl3.innerHTML = "Not a valid e-mail address";
         flag = 1;
     }
Check if the date is greater than today: You check the entered date with the date object of the java script as shown below:
var DOJ = new Date(inputDOJ.value);
var todaydate = new Date();
var month = todaydate.getMonth() + 1;
var today = new Date(month + '/' + todaydate.getDate() + '/' + todaydate.getFullYear());
if ((inputDOJ.value == "") || (DOJ < today)) 
     {
          lbl2.innerHTML = "Date should be greater than today"
          flag = 1;
     }
Check the values to be distinct: You can check if the entered values in the two fields are distinct by using the following code:
   if (reportingmanger.value == employeeid.value)
      {
         lbl6.innerHTML = "Reporting MangerID should not be same as EmployeeID";
          flag = 1;
      }
Check if the values in the fields are blank: Javascript can be used to make the fields as mandatory by using the following code snippet.
if (reportingmanger.value == "") 
      {
         lbl6.innerHTML = "ReportingManagerID cannot be blank";
         flag = 1;
      }
Check the length of employeeid:Length of the value entered in the field can be checked by using 'lenght' property.
if ((employeeid.value == "" ) ||  (employeeid.value.length != 4))
     {
            lbl1.innerHTML = "Please Enter Valid 4 digit EmployeeID";
            flag = 1;
     }

JavaScript Client API for Asp.net Validation Controls:

In the above we have written the code from the scratch to perfom validations. But the asp.net comes with in built validations controls to perfrom validations. Now by usign the client side api of validations we can use the controls without post back.
Page_ClientValidate(val) method and Page_IsValid property is used for this task as shown below:
        function performCheck() 
        {
          Page_ClientValidate("DemoValidate");
          if (Page_IsValid) 
          {
              alert('Form Submitted Succesfully');
              return true;
          }
          else 
          {
              alert('Please Correct The errors');
             return false;
          }
        }
    
The above function can be called on page submission as shown below:
      <asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="DemoValidate" OnClientClick ="performCheck()" />
      
Note: ValidationGroup property should be same for all the validation controls across the group which are need to be validated.

Javascript parsing:

The following code can be used to call the javascript from code behind using c# code.
       //c# code:
        public void InvokeMethod()
        {
            string name = "HelloWorld";
            Button1.Attributes.Add("OnClick", "javascript:return displayalert('" +  name + "')");
        }

        // javascript function
        function displayalert(text)
        {
            alert(text);
            return false;
        }
By using the following code snippet java script function can be called on the page load:
ScriptManager.RegisterStartupScript(Page,this.GetType(),"fid", "displayalert('Helloworld');", true);
The following code is used to call c# function by using javascript.
    // c# function
    public string displayalert()
    {
        string name = "HelloWorld";
        return name;
    }
    // javascript function to call c# code.
    function Title()
    {
        var str ='<%= displayalert()%>';
        alert(str);
    }
Note:Only method with return types can be called from the java script.

Pass the C# variables to JavaScript array:

Sometime often if you want to send the elements of any c# collection class to javascript array, you can use the following code: c# code:
Declare Variables:
ArrayList states = new ArrayList();
protected string s = string.Empty;


    private void SendData() 
    {
        
        // Add the values to the arraylist.
        
        states.Add("AndhraPradesh");
        states.Add("HimachalPradesh");
        states.Add("Gujarat");
        states.Add("MadhyaPradesh");
        foreach (string state in states)
        {
            if (s == string.Empty)
            {
                s = "\""+state+"\"";
            }
            else
            {
                s = s +","+"\""+ state+"\"";
            }
        }
    }

JavaScript Code
        function initializedate()
        {
             var statelist = [<% = s %>];  
             var s="";
             for(var i=0;i<statelist.length;i++)
             {
                 s = s +"<br/>"+ statelist[i];
             }
            var text = document.getElementById("Text1"); 
            text.innerHTML = s;
            return false;
        }
        window.onload = initializedate;
        <div id  ="Text1"> </div>

Conclusion:

In this article some of commonly used javascript techniqes used in asp.net applications. In the next "Javascirpt create user wizard for Asp.Net" you can learn how to create a custom create user wizard by using simple javascript code. In Further revesions some more techniques would added in this article. For more clarification you can download and go through the code.

No comments:

Post a Comment