Calling C# Function From JQuery

Sample Code to call C# function from JQuery

ASPX Page Code

<html xmlns="">
<head runat="server">
    <%--CSS & Script Start--%>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <script src=""></script>
    <script src=""></script>
    <%--CSS & Script End--%>

    <%--Jquery Call Start--%>
    <script type="text/javascript">

        function UserLogin() {

            var user = $('#username').val();
            var pass = $('#password').val();

                type: "POST",
                url: "Default.aspx/UserLogin",
                data: JSON.stringify({ username: user, password: pass }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: onSuccess,
                failure: function (AjaxResponse) {
                    alert("Failed: " + AjaxResponse.d);
            function onSuccess(AjaxResponse) {
                $("#Result").html("Output Result: " + AjaxResponse.d);

            return false;

    <%--Jquery Call End--%>
    <%--Sample HTML Form Start--%>
    <h2>Login form</h2>
    <form id="form1" runat="server">
            <div class="form-group">
                <label for="username">Username:</label>
                <input class="form-control" id="username" placeholder="Enter Username">
            <div class="form-group">
                <label for="pwd">Password:</label>
                <input type="password" class="form-control" id="password" placeholder="Enter password">
            <button type="submit" class="btn btn-default" onclick="return UserLogin()">Submit</button>
        <%--Sample HTML Form End--%>
        <%--Result Div Start --%>
        <div id="Result" style="background-color:antiquewhite">
        <%--Result Div End --%>

C# Code behind File

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

    public static string UserLogin(string username,string password)
        return "You enter Username : " + username + "& Password :" + password;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s