JQuery: Consuming Page Method in ASP.Net


jquery1

Introduction: Page Method is an easy way to communicate with the code behind and JQuery functions for simple operations. Although it can be done using web services or WCF but, for simple operations there is no need to complicate things. This post is a simple demo of how we can consume page methods in ASP.Net using AJAX. Note: This example produces summation of two inputted integers as result and I know in real life this logic is not going to help you but, as I already said my intention is to show only a way to consume page methods with JQuey using AJAX so, you can definitely replace your logic here.

Demo:
1. Place two Textbox(ID: txtNum1, txtNum2) and a Button (ID: btnSum) in the page.

<div>Enter two integers and click <strong>SUM</strong> button to get the result
<div style="padding: 5px;">First Number</div>
<div style="padding: 5px;">Second Number</div>
</div>

2. Create a page method (SumIntegers()) in code behind with two integer parameters named num1 and num2. Don’t forget to assign [WebMethod()] attribute to it for which you need to add namespace System.Web.Services and to call the page method directly make it static.

using System;
using System.Web.Services;

public partial class WebMethodDemo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e){}

    [WebMethod()]
    public static int SumIntegers(int num1, int num2)
    {
        return num1 + num2;
    }
}

3. Now the last thing to do is to write the JQuery section where we will be able to call the ajax method to get the desired result.

<script type="text/javascript">// <![CDATA[
        $(document).ready(function () {
            $("#btnSum").click(function (e) {

                var num1 = $("#txtNum1").val();
                var num2 = $("#txtNum2").val();
                $.ajax({
                    type: "POST",
                    url: window.location.href + "/SumIntegers",
                    data: '{"num1":"' + num1 + '","num2":"' + num2 + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        alert(num1+"+"+num2+"="+msg.d);
                    },
                    error: function () {
                        alert("Error occured. Please check inputs !");
                    }
                });
            });
        });

// ]]></script>

Explanation: As you may know, $(document).ready() function gets executed as soon as DOM is loaded and before the page contents are rendered in to the browser. We need to embed all the JQuery markup inside this function. Define an event handler for click event of button ‘btnSum’. Rest of the logic is written inside this event handler as we want to execute our logic on clicking the button. First retrieve the values from the textboxes. Now to perform the asynchronous HTTP(ajax) request, call the .ajax() method of JQuery with the url and necessary settings. If the ajax call succeeds then we can get the returned result using msg.d as the result will always be enclosed within the ‘d’ (since ASP.Net 3.5, which prevents direct execution of the string as script).

Downloads: Demo Project Download

I hope this is useful.

Thanks for reading and please don’t forget to add a comment.

Advertisements

Javascript: Thousand separator


We may use following javascript function to show numbers formatted with thousands separator.

Definition

function formatThousandPlace(orgNum) {
    arr = orgNum.split('.');    //split integer part &amp; fractional part
    intPart = arr[0];           //store integer part in a variable
    fractionPart = arr.length > 1 ? '.' + arr[1] : '';  //store fractional part in a variable
    var rgx = /(\d+)(\d{3})/;   //regexp to find thousand place
            
    while (rgx.test(intPart)) { 
        intPart = intPart.replace(rgx, '$1' + ',' + '$2');  //replace integer part after inserting a comma in the thousandth place
    }
    
    document.write(intPart + fractionPart); //write final value to the document
}

Function Call
Now, we can use it anywhere in the document where we want to show those numbers. For example: it may inside normal html elements or some dynamic ASP.Net controls like GridView, DataList, FormView etc.

<script language="javascript">formatThousandPlace('10000000.00')</script>

While calling this from ItemTemplate of an ASP GridView the syntax will be

<asp:TemplateField HeaderText="Price">
    <ItemTemplate>
       <script language="javascript">formatThousandPlace('<%#Eval("SalePrice") %>')</script>
    </ItemTemplate>
</asp:TemplateField>

I hope this is helpful.

Javascript: Function to get current fiscal year


This can be useful when you need to print current session year or, current fiscal/financial year somewhere in your page and specifically when you do not want to invoke a server method for it.

Defining Function


<script language="javascript">
 function getCurrentFiscalYear() {
    //get current date
    var today = new Date();
    
    //get current month
    var curMonth = today.getMonth();
    
    var fiscalYr = "";
    if (curMonth > 3) { //
        var nextYr1 = (today.getFullYear() + 1).toString();
        fiscalYr = today.getFullYear().toString() + "-" + nextYr1.charAt(2) + nextYr1.charAt(3);
    } else {
        var nextYr2 = today.getFullYear().toString();
        fiscalYr = (today.getFullYear() - 1).toString() + "-" + nextYr2.charAt(2) + nextYr2.charAt(3);
    }
    
    document.write(fiscalYr);
 }
 </script>

Calling Function

<script language="javascript">getCurSession()</script>

Note:

  • I have made the function as per Indian fiscal year. You can change it according to your country. You only need to modify the conditional statement i.e, if (curMonth > 3) where April(3) is the starting month of fiscal year.
  • getMonth() returns number of the month in a date value starting from 0 to 11
  • You can change this function to return the session year which can be input for another logic/function. Accordingly you have to change the function.

JavaScript Validation: Date Range


This quick post shows how to validate two date fields by comparing their values. When there is two date fields in a page like From Date & To Date , then generally arises a requirement to show a message that From Date can not be greater than To Date or, something like that. This is required when the user inputs a greater date in  the From Date field than To Date.

Example:

Here I have taken two TextBox for inputting dates named- txtFromDate & txtToDate

var FromDt = document.getElementById("<%=txtFromDate.ClientID %>").value;
var ToDt = document.getElementById("<%=txtToDate.ClientID %>").value;

if (Date.parse(FromDt.trim()) > Date.parse(ToDt.trim())) {
    alert("Please check date range!\nFrom Date cannot be greater than To Date!")
    return false;
}