Code2night
  • Home
  • Blogs
  • Tutorial
  • Post Blog
  • Tools
    • Json Beautifier
    • Html Beautifier
  • Members
    • Register
    • Login
  1. Home
  2. Blogpost
21 Feb
2021

Using Ajax in Asp.Net MVC

by Shubham Batra

3550

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.

  • |
  • Jquery AJax , Ajax , Jquery , AspNet , MVC

Comments

Tags

How to set Date and time format in IIS Manager
IIS Manager
IIS
Internet Information Services (IIS) Manager
Internet Information Services (IIS)
Internet Information Services
Error Handling In AspNet Core
Exception Handling Asp Net Core
Exception Handling
Exception Handling Asp Net
Aspnet
Creating Log Files in MVC
Error Handling in MVC
Exception Handling in AspNet
Handling Exceptions and Creating Error Logs in Asp net Mvc using base controller
net
Code2Tonight
Stopping Browser Reload On Save
Repository Pattern with ADONet in MVC
Repository Pattern With ASPNET MVC And AdoNet
MVC Crud Operation
Jquery Full Calender Integrated With ASPNET
Full Calendar
Jquery Calendar
Slick Slider
Slick Slider Example
responsive carousels
Entity Framework
MVC
Intergrate SummerNote Text Editor into AspNet MVC
Web Config
Auto Redirection
Redirection from Http to https
AspNet
Url Rewriting
Implement Stripe Payment Gateway In ASPNET Core
Stripe Payment Gateway
C#
AspNet Core
StripeNet
Postgre
PgAdmin4
PostgreSql
A Non Fatal Error Occured During Cluster Initialisation In Postgre SQL
Microsoft Outlook
Outlook Appointments
Microsoft Exchange Service
Send Email With HTML Template And PDF Using ASPNet C#
Send Email
Email with html template
email with pdf attachment
email with html and pdf
Microsoft Outlook Contacts
Outlook
Microsoft Exhchange Service
JSON
Convert string with dot notation to JSON
HTTP Error 5025 ANCM Out Of Process Startup Failure
Internet Information Service
Net core
Payumoney Integration With AspNet MVC
Prism js
Highlighting Syntax
Syntax Highlighting
code stylings
c#
Jquery AJax
Ajax
Jquery
Implement Stripe Payment Gateway In ASPNET
Using Checkout in an ASPNET Web Forms application
Stripe Payment
Stripe Payment Integration
Stripe Integeration
How to upload Image file using AJAX andjQuery
upload Image file using AJAX and jquery
Ajax call
file upload using ajax
file uploading using ajax and jquery
ConfigurationBuilder does not contain a definition for SetBasePath
Reading app json file in dot net core
Appsetting jso
Dot Net Core
Globalization and localization in ASPNET Core
Asp Net Core with Resource file resx
How to get the resx file strings in asp net core
Culture in Net core
Localisation in AspNet Core
Url Encryption in AspNet MVC
Url Encryption in C#
Url Encryption
Custom Helpers
Slick Slider with single slide
Slick
Vue js
Child Components
How to reload vue js child components
Net Core
Visual Studio
Net core 31
Razor
Zoom sdk
Zoom c# wrapper Inegration
zoom Integration in c#
Zoom Integration
Zoom window sdk
vue js toggle button
vue js
toggle buttons
vuejs
vue js toggle switch
SignalR
VueJs
SignalR in Net Core
Chat App in Vue js
Chat App using SignalR
AspNet Chat app
JPlayer
Html5 Audio Video Player
Music Player
QR Code Generator
QR Code
Jquery QR Code
AspNet MVC
Google Maps
Google map api
Places API
Google map Places API in AspNet
Jquery Autocomplete
Autocomplete
Jquery UI Autocomplete
ExcelDataReader
Import data from excel in AspNet
Card Number Formatting
Amex Card Format
Card Format
FCM
Cloud Messaging
Android Notifications
FCM Notifications for IOS
IOS Notifications
Angular js
apply css on child components in Angular js
Angular Mentions
Google Sign In
Google Login
Google Oauth Api
Social Login
Aspnet Mvc
Google + Api
Create and publish a package using Visual Studio (NET Framework
Windows)
Create and publish a nuget package
create your own nuget package
Image compress
Image optimization
compress Image
optimize Image
WebForm
AspNet Web Pages
Batch Script
Database backup
Powershell
ASpNet
Sql Server Backup
AspNet core 31
Aspnet core 21
HttpCookies in AspNet Core
LinkedIn Authentication
Login using LinkedIN
Social Login in AspNet
LinkedIn Authentication in AspNet MVC
LinkedIn Login in aspnet MVC
Shuffle List in c#
C#Net
Google Login in AspNet MVC
GoogleAuthentication Nuget package
Password Encryption
RFC Encryption
Encryption and Decryption
Encryption in AspNet
Base 64 Encryption
Base 64 Decryption
Swagger UI
Swashbuckle
SwashbuckleAspNetCore
Rest API
Postman
Api Testing
SSRS
SSRS Report
ASPNET MVC
ASPNET MVC SSRS Report
ssrs report
XlWorkbook
ClosedXml
Excel Export
Blazor
Syncfusion
SFGrid
Syncfusion SFgrid
Net
Net core 60
DataTable to List
Extension Methods
Microsoft Access Database Engine
Ace Ole Db 120
MicrosoftACEOLEDB120
OLE DB
Aspnet MVC
Ace OLE DB

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

  • Kurukshetra
  • [email protected]

Links

  • Home
  • Blogs
  • Tutorial
  • Post Blog

Popular Tags

Copyright © 2022 by Code2night. All Rights Reserved

  • Home
  • Blog
  • Login
  • SignUp
  • Contact
  • Json Beautifier