Using Ajax in Asp.Net MVC | Code2night.com
Code2night
  • Home
  • Blogs
  • Guest Posts
  • Tutorial
  • Post Blog
  • Register
  • Login
  1. Home
  2. Blogpost

Using Ajax in Asp.Net MVC

Date- Feb 21,2021

17802

Jquery AJax Ajax

Ajax 

So starting of from the beginning Ajax is used for Asynchronous Javascript and XML. We can use it for many purposes. Few basic uses of Ajax are:-

  • Update page without reloading the page providing better performance.
  • Request data from a server - after the page has loaded which can be used in loading Partial Views.
  • Send data to a server without reload - in the background making it easier to performance Save, Delete operations smoothly.

Ajax in Asp.Net MVC

Ajax can be used anywhere where we can use jquery. But we will be watching few examples of different ways of using Ajax in Asp.Net MVC. We will be posting data on MVC Controller without refreshing the page. So let's start from beginning:-

Step-1


So , first of all we will be creating a new view and adding few field on it . Now we will be trying to send the values of these fields on controller without reload and especially using Ajax.

So We will add a new view and few fields on it.

@{
    ViewBag.Title = "Home Page";
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="jumbotron">
    <h2>Ajax Call Getting started</h2>
</div>

<div class="form-group">
    <label for="email">Employee Id:</label>
    <input type="text" class="form-control" id="txtId" placeholder="Enter Employee Id" name="email">
</div>
<div class="form-group">
    <label for="pwd">Employee Name:</label>
    <input type="text" class="form-control" id="txtName" placeholder="Enter Employee Name" name="pwd">
</div>
<div class="form-group">
    <label for="pwd">Employee Salary:</label>
    <input type="text" class="form-control" id="txtSalary" placeholder="Enter Employee Salary" name="pwd">
</div>
<input type="button" id="btnGet" class="btn btn-success" value="Ajax Call Type 1" />
<input type="button" id="btnGet2" class="btn btn-success" value="Ajax Call Type 2" />
<input type="button" id="btnGet3" class="btn btn-success" value="Ajax Call Type 3" />
<input type="button" id="btnGet4" class="btn btn-success" value="Ajax Call Type 4" />
<input type="button" id="btnGet5" class="btn btn-success" value="Ajax Call Type 5" />

<script type="text/javascript">
    $(function () {
        $("#btnGet").click(function () {
            var empIds = $("#txtId").val();
            var empNames = $("#txtName").val();
            var empSalarys = $("#txtSalary").val();
            $.ajax({
                type: "POST",
                url: "/Home/AjaxMethod",
                data: '{empId: "' + empIds + '" , empName: "' + empNames + '" , empSalary: "' + empSalarys + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert("Hello: " + response.EmpName + " Your Employee Id Is: " + response.EmpId + "And Your Salary Is: " + response.EmpSalary);
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        });
    });

    // second
    $(function () {
        $("#btnGet2").click(function () {
            debugger;
            var empIds = $("#txtId").val();
            var empNames = $("#txtName").val();
            var empSalarys = $("#txtSalary").val();
            $.ajax({
                url: "/Home/AjaxMethod",
                dataType: "json",
                type: "POST",
                cache: false,
                data: { empId: empIds, empName: empNames, empSalary: empSalarys },
                success: function (response) {
                    alert("Hello: " + response.EmpName + " Your Employee Id Is: " + response.EmpId + "And Your Salary Is: " + response.EmpSalary);
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            })
        })
    });


    //third
    $(function () {
        $("#btnGet3").click(function () {
            var intrestedInAll =
            {
                EmpId: $("#txtId").val(),
                EmpName: $("#txtName").val(),
                EmpSalary: $("#txtSalary").val(),
            };
            debugger;
            $.ajax({
                url: '/Home/AjaxMethodWithObject',
                type: 'POST',
                data: { "queryFilter": JSON.stringify(intrestedInAll) },
                cache: false,
                success: function (response) {
                    alert("Hello: " + response.EmpName + " Your Employee Id Is: " + response.EmpId + "And Your Salary Is: " + response.EmpSalary);
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        });
    });

    //fourth

    $(function () {
        $("#btnGet4").click(function () {
            var personModel =
            {
                EmpId: $("#txtId").val(),
                EmpName: $("#txtName").val(),
                EmpSalary: $("#txtSalary").val(),
            };
            personModel = JSON.stringify(personModel);
            debugger;
            $.ajax({
                type: "POST",
                url: "/Home/AjaxMethodWithModel",
                data: personModel,
                dataType: "json",
                contentType: 'application/json; charset=utf-8',
                success: function (response) {
                    alert("Hello: " + response.EmpName + " Your Employee Id Is: " + response.EmpId + "And Your Salary Is: " + response.EmpSalary);
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        });
    });

    //fifth
    function GetAjaxDataPromise(url, postData) {
        debugger;
        var promise = $.post(url, postData, function (promise, status) {
        });
        return promise;
    };
    $(function () {
        $("#btnGet5").click(function () {
            debugger;
            var promises = GetAjaxDataPromise('@Url.Action("AjaxMethod", "Home")', { EmpId: $("#txtId").val(), EmpName: $("#txtName").val(), EmpSalary: $("#txtSalary").val() });
            promises.done(function (response) {
                debugger;
                alert("Hello: " + response.EmpName + " Your Employee Id Is: " + response.EmpId + "And Your Salary Is: " + response.EmpSalary);
            });
        });
    });

</script>

So this a view we have added with few fields and few jquery methods that we will be learning next in blog. So we will see parts of this view one by one with usings. So the first section showed below is used to add input fields on the View. You can add fields according to your requirement. For this example we will be adding 3  input fields on the view.

@{ ViewBag.Title = "Home Page";
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="jumbotron">
    <h2>Ajax Call Getting started</h2>
</div>

<div class="form-group">
    <label for="email">Employee Id:</label>
    <input type="text" class="form-control" id="txtId" placeholder="Enter Employee Id" name="email">
</div>
<div class="form-group">
    <label for="pwd">Employee Name:</label>
    <input type="text" class="form-control" id="txtName" placeholder="Enter Employee Name" name="pwd">
</div>
<div class="form-group">
    <label for="pwd">Employee Salary:</label>
    <input type="text" class="form-control" id="txtSalary" placeholder="Enter Employee Salary" name="pwd">
</div>

So After adding the fields we have added five different button. All of them will be used for posting input fields data on controller but we will be using different way of using Ajax in all buttons. You can add these buttons to your view which are calling jquery methods on click.

<input type="button" id="btnGet" class="btn btn-success" value="Ajax Call Type 1">
<input type="button" id="btnGet2" class="btn btn-success" value="Ajax Call Type 2">
<input type="button" id="btnGet3" class="btn btn-success" value="Ajax Call Type 3">
<input type="button" id="btnGet4" class="btn btn-success" value="Ajax Call Type 4">
<input type="button" id="btnGet5" class="btn btn-success" value="Ajax Call Type 5">

So when you will click first button . This jquery click event will be fired and as you can say we have used ajax in this method. So you can understand  while using Ajax we need few thing to describe there. We need URL where we need to post data. Url entered in this method means  Home is controller and AjaxMethod is the Action name.

Data - This is where you have to pass the data you want to post on controller . As you can see we have to send data in JSON format.

So while using JSON you have to specify key and value pair. Remember the key you secify here must be same which you have used as parameter in controller. We will be watching how to receive these posted values in controller action.

 $(function () {
        $("#btnGet").click(function () {
            var empIds = $("#txtId").val();
            var empNames = $("#txtName").val();
            var empSalarys = $("#txtSalary").val();
            $.ajax({
                type: "POST",
                url: "/Home/AjaxMethod",
                data: '{empId: "' + empIds + '" , empName: "' + empNames + '" , empSalary: "' + empSalarys + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert("Hello: " + response.EmpName + " Your Employee Id Is: " + response.EmpId + "And Your Salary Is: " + response.EmpSalary);
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        });
    });

So the data posted in previous jquery ajax method is posted to this action method.You can see we have added same parameters which we have posted previously from jquery method.

 [HttpPost]
        public JsonResult AjaxMethod(string empId, string empName, string empSalary)
        {
            PersonModel person = new PersonModel
            {
                EmpId = empId,
                EmpName = empName,
                EmpSalary = empSalary
            };
            return Json(person);
        }

Method-2
So In this method we have made some changes in the data values. Earlier we were using JSON syntax for sending data while in this we will simply send data in the form of object. This is more simpler way of sending data as not many syntax issues in this. Apart from how we adding parameters not much difference here.

 // second
    $(function () {
        $("#btnGet2").click(function () {
            debugger;
            var empIds = $("#txtId").val();
            var empNames = $("#txtName").val();
            var empSalarys = $("#txtSalary").val();
            $.ajax({
                url: "/Home/AjaxMethod",
                dataType: "json",
                type: "POST",
                cache: false,
                data: { empId: empIds, empName: empNames, empSalary: empSalarys },
                success: function (response) {
                    alert("Hello: " + response.EmpName + " Your Employee Id Is: " + response.EmpId + "And Your Salary Is: " + response.EmpSalary);
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            })
        })
    });

So the data posted in object form is received in the same format we have used in last method. Not many changes here but remember keys must be same and also HttpPost. must be used.

 [HttpPost]
        public JsonResult AjaxMethod(string empId, string empName, string empSalary)
        {
            PersonModel person = new PersonModel
            {
                EmpId = empId,
                EmpName = empName,
                EmpSalary = empSalary
            };
            return Json(person);
        }

Method-3
So , The third way of sending data to controller is used when we want to receive data in model parameter. For that we can create jquery object and than use jquery stringify to convert that to json and post.

  //third
    $(function () {
        $("#btnGet3").click(function () {
            var intrestedInAll =
            {
                EmpId: $("#txtId").val(),
                EmpName: $("#txtName").val(),
                EmpSalary: $("#txtSalary").val(),
            };
            debugger;
            $.ajax({
                url: '/Home/AjaxMethodWithObject',
                type: 'POST',
                data: { "queryFilter": JSON.stringify(intrestedInAll) },
                cache: false,
                success: function (response) {
                    alert("Hello: " + response.EmpName + " Your Employee Id Is: " + response.EmpId + "And Your Salary Is: " + response.EmpSalary);
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        });
    });

So when post jquery object in json form we can add model to action parameters. Remember properties of model must be same like jquery object we have posted.
.
 [HttpPost]
        public JsonResult AjaxMethodWithObject(string queryFilter)
        {
            PersonModel personModel = JsonConvert.DeserializeObject<PersonModel>(queryFilter);

            return Json(personModel);
        }
Method-4
So in this method we will be posting jquery object without using stringify. This method is better as this minimizes complex syntax while achieving same working.
 //fourth

    $(function () {
        $("#btnGet4").click(function () {
            var personModel =
            {
                EmpId: $("#txtId").val(),
                EmpName: $("#txtName").val(),
                EmpSalary: $("#txtSalary").val(),
            };
            personModel = JSON.stringify(personModel);
            debugger;
            $.ajax({
                type: "POST",
                url: "/Home/AjaxMethodWithModel",
                data: personModel,
                dataType: "json",
                contentType: 'application/json; charset=utf-8',
                success: function (response) {
                    alert("Hello: " + response.EmpName + " Your Employee Id Is: " + response.EmpId + "And Your Salary Is: " + response.EmpSalary);
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        });
    });

So the receiving part for this method is same as previous one. Not many changes here.

  [HttpPost]
        public JsonResult AjaxMethodWithModel(PersonModel personModel)
        {
            PersonModel person = new PersonModel
            {
                EmpId = personModel.EmpId,
                EmpName = personModel.EmpName,
                EmpSalary = personModel.EmpSalary
            };
            return Json(person);
        }

Method-5
This method is one of the best we can use as it allows us to post data to separate parameters as well as Model with same code.You have to pass the url and data as jquery object.The following example is with jquery promise. 

    //fifth
    function GetAjaxDataPromise(url, postData) {
        debugger;
        var promise = $.post(url, postData, function (promise, status) {
        });
        return promise;
    };
    $(function () {
        $("#btnGet5").click(function () {
            debugger;
            var promises = GetAjaxDataPromise('@Url.Action("AjaxMethod", "Home")', { EmpId: $("#txtId").val(), EmpName: $("#txtName").val(), EmpSalary: $("#txtSalary").val() });
            promises.done(function (response) {
                debugger;
                alert("Hello: " + response.EmpName + " Your Employee Id Is: " + response.EmpId + "And Your Salary Is: " + response.EmpSalary);
            });
        });
    });
So as we have told earlier the data posted from last method can be received with both the ways  You can try that and comment if you have any issues.
 [HttpPost]
        public JsonResult AjaxMethod(string empId, string empName, string empSalary)
        {
            PersonModel person = new PersonModel
            {
                EmpId = empId,
                EmpName = empName,
                EmpSalary = empSalary
            };
            return Json(person);
        } 
[HttpPost]
        public JsonResult AjaxMethodWithModel(PersonModel personModel)
        {
            PersonModel person = new PersonModel
            {
                EmpId = personModel.EmpId,
                EmpName = personModel.EmpName,
                EmpSalary = personModel.EmpSalary
            };
            return Json(person);
        }

The complete code for controller is

  public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult AjaxMethod(string empId, string empName, string empSalary)
        {
            PersonModel person = new PersonModel
            {
                EmpId = empId,
                EmpName = empName,
                EmpSalary = empSalary
            };
            return Json(person);
        }


        [HttpPost]
        public JsonResult AjaxMethodWithObject(string queryFilter)
        {
            PersonModel personModel = JsonConvert.DeserializeObject<PersonModel>(queryFilter);

            return Json(personModel);
        }

        [HttpPost]
        public JsonResult AjaxMethodWithModel(PersonModel personModel)
        {
            PersonModel person = new PersonModel
            {
                EmpId = personModel.EmpId,
                EmpName = personModel.EmpName,
                EmpSalary = personModel.EmpSalary
            };
            return Json(person);
        }
    }

Response-

So When jquery ajax request completed you can check the response from success method. You can check in the examples above. So this is how we can use Ajax in Asp.Net MVC.

Comments

Tags

LinkedinLogin
LinkedinProfile
GetLinkedinProfile
C#
Aspnet
MVC
Linkedin
ITextSharp
Export to Pdf
AspNet Core
AspNet
View to Pdf in Aspnet
Model Validation In ASPNET Core MVC 60
Model Validation
Model Validation In ASPNET Core MVC
Model Validation In ASPNET
Image Compression in AspNet
Compress Image in c#
AspNet MVC
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1210
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp Join Us On Facebook

Welcome To Code2night, A common place for sharing your programming knowledge,Blogs and Videos

  • Panipat
  • info@Code2night.com

Links

  • Home
  • Blogs
  • Tutorial
  • Post Blog

Popular Tags

Copyright © 2025 by Code2night. All Rights Reserved

  • Home
  • Blog
  • Login
  • SignUp
  • Contact
  • Terms & Conditions
  • Refund Policy
  • About Us
  • Privacy Policy
  • Json Beautifier
  • Guest Posts