Chuyển tới nội dung
Home » Ajax Syntax In Mvc | Ajax Call Getting Started

Ajax Syntax In Mvc | Ajax Call Getting Started

(#39) Get data using ajax in mvc | mvc tutorial for beginners in .net c#

The ASP File

The page on the server called by the JavaScript above is an ASP file called “getcustomer.asp”.

The source code in “getcustomer.asp” runs a query against a database, and returns the result in an HTML table:

response.expires=-1

sql=”SELECT * FROM CUSTOMERS WHERE CUSTOMERID=”

sql=sql & “‘” & request.querystring(“q”) & “‘”

set conn=Server.CreateObject(“ADODB.Connection”)

conn.Provider=”Microsoft.Jet.OLEDB.4.0″

conn.Open(Server.Mappath(“/datafolder/northwind.mdb”))

set rs=Server.CreateObject(“ADODB.recordset”)

rs.Open sql,conn

response.write(”

“)

do until rs.EOF

for each x in rs.Fields

response.write(”


” & x.name & ”

“)

response.write(”

” & x.value & ”

“)

next

rs.MoveNext

loop

response.write(“”)

%>

Try it Yourself – Examples

Use the async settingHow to use the async setting to specify a synchronous request

Make an AJAX request with a specified data typeHow to use the dataType setting to specify the data type for the request.

Make an AJAX request with an errorHow to use the error setting to deal with errors in an AJAX request.

The usage of AJAX in ASP.net is fast growing these days as it helps you to create more dynamic, responsive, and better web applications. By using AJAX in ASP.net, the performance of an application is highly increased as the response time is reduced and the traffic between the server and the client is reduced as well.

You will now learn what AJAX is in ASP.net, its advantages and disadvantages, and how to transfer the data through AJAX in ASP.net.

(#39) Get data using ajax in mvc | mvc tutorial for beginners in .net c#
(#39) Get data using ajax in mvc | mvc tutorial for beginners in .net c#

What Is AJAX in ASP.net?

AJAX in ASP.net stands for Asynchronous JavaScript and XML. This technique is used to develop rich web applications that are interactive, responsive, and dynamic in nature.

By the method of receiving and sending data to the server in the background, the web pages are updated using AJAX in ASP.net. Without even reloading the web page, you will be able to update the website part by part as well. This update of the website is done asynchronously using AJAX in ASP.net.

In AJAX, usually, multiple technologies are used together to create these dynamic web pages. Some of these technologies include –

  • XSLT
  • XHTML
  • CSS
  • JavaScript
  • Document Object Model
  • XML
  • XMLHttpRequest object

The interactive animation that you see on modern web pages is mainly because of AJAX. In common web pages that do not use AJAX, one needs to reload the entire web page in order to reflect content changes in any parts or all. Now, you are going to discuss the advantages, disadvantages of AJAX in ASP.net and how to transfer data through AJAX in ASP.net.

How to Transfer the Data Through AJAX?

Now, look at the implementation of transferring data through AJAX in ASP.net.

There are two ways in which we can transfer data through AJAX –

  1. Server to Client
  2. Client to Server

Now, you will see how to apply and implement both of these ways.

Consider an entity – Student which contains two fields: ID and Name.

Code Snippet

public class Student

public int ID { get; set; }

public string Name { get; set; }

(#42) @Ajax.BeginForm in MVC | mvc tutorial for beginners in .net c#
(#42) @Ajax.BeginForm in MVC | mvc tutorial for beginners in .net c#

Create an Unobtrusive Ajax Application

In the example that follows, we will create a form which will display the list of users in the system. We will place a dropdown having three options: Admin, Normal, and Guest. When you will select one of these values, it will display the list of users belonging to this category using unobtrusive AJAX setup.

Step 1 − Create a Model file Model.cs and copy the following code.

using System; namespace MVCAjaxSupportExample.Models { public class User { public int UserId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime BirthDate { get; set; } public Role Role { get; set; } } public enum Role { Admin, Normal, Guest } }

Step 2 − Create a Controller file named UserController.cs and create two action methods inside that using the following code.

using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using MVCAjaxSupportExample.Models; namespace MVCAjaxSupportExample.Controllers { public class UserController : Controller { private readonly User[] userData = { new User {FirstName = “Edy”, LastName = “Clooney”, Role = Role.Admin}, new User {FirstName = “David”, LastName = “Sanderson”, Role = Role.Admin}, new User {FirstName = “Pandy”, LastName = “Griffyth”, Role = Role.Normal}, new User {FirstName = “Joe”, LastName = “Gubbins”, Role = Role.Normal}, new User {FirstName = “Mike”, LastName = “Smith”, Role = Role.Guest} }; public ActionResult Index() { return View(userData); } public PartialViewResult GetUserData(string selectedRole = “All”) { IEnumerable data = userData; if (selectedRole != “All”) { var selected = (Role) Enum.Parse(typeof (Role), selectedRole); data = userData.Where(p => p.Role == selected); } return PartialView(data); } public ActionResult GetUser(string selectedRole = “All”) { return View((object) selectedRole); } } }

Step 3 − Now create a partial View named GetUserData with the following code. This view will be used to render list of users based on the selected role from the dropdown.

@model IEnumerable

@foreach (var item in Model) {

}

@Html.DisplayNameFor(model => model.FirstName) @Html.DisplayNameFor(model => model.LastName) @Html.DisplayNameFor(model => model.BirthDate)
@Html.DisplayFor(modelItem => item.FirstName) @Html.DisplayFor(modelItem => item.LastName) @Html.DisplayFor(modelItem => item.BirthDate)

Step 4 − Now create a View GetUser with the following code. This view will asynchronously get the data from the previously created controller’s GetUserData Action.

@using MVCAjaxSupportExample.Models @model string @{ ViewBag.Title = “GetUser”; AjaxOptions ajaxOpts = new AjaxOptions { UpdateTargetId = “tableBody” }; }

Ajax Call Getting started

$(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); } }); }); });

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

// 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); } }) }) });

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

//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); } }); }); });

[HttpPost] public JsonResult AjaxMethodWithObject(string queryFilter) { PersonModel personModel = JsonConvert.DeserializeObject (queryFilter); return Json(personModel); }

//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); } }); }); });

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

//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); }); }); });

[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 (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.

  • MVC Framework Tutorial
  • MVC Framework – Home
  • MVC Framework – Introduction
  • MVC Framework – Architecture
  • MVC Framework – ASP.NET Forms
  • MVC Framework – First Application
  • MVC Framework – Folders
  • MVC Framework – Models
  • MVC Framework – Controllers
  • MVC Framework – Views
  • MVC Framework – Layouts
  • MVC Framework – Routing Engine
  • MVC Framework – Action Filters
  • Advanced Example
  • MVC Framework – Ajax Support
  • MVC Framework – Bundling
  • Exception Handling
  • MVC Framework Useful Resources
  • Questions & Answers
  • MVC Framework – Quick Guide
  • MVC Framework – Resources
  • MVC Framework – Discussion

MVC Framework – Ajax Support

As you might be knowing, Ajax is a shorthand for Asynchronous JavaScript and XML. The MVC Framework contains built-in support for unobtrusive Ajax. You can use the helper methods to define your Ajax features without adding a code throughout all the views. This feature in MVC is based on the jQuery features.

To enable the unobtrusive AJAX support in the MVC application, open the Web.Config file and set the UnobtrusiveJavaScriptEnabled property inside the appSettings section using the following code. If the key is already present in your application, you can ignore this step.

After this, open the common layout file _Layout.cshtml file located under Views/Shared folder. We will add references to the jQuery libraries here using the following code −

Use jQuery AJAX in ASP.NET CORE 6?  You NEED to see how it´s done!
Use jQuery AJAX in ASP.NET CORE 6? You NEED to see how it´s done!

Get User

@Html.Action(“GetUserData”, new {selectedRole = Model })
First Last Role

@using (Ajax.BeginForm(“GetUser”, ajaxOpts)) {

@Html.DropDownList(“selectedRole”, new SelectList( new [] {“All”}.Concat(Enum.GetNames(typeof(Role)))))

}

Step 5 − Finally, change the Route.config entries to launch the User Controller.

defaults: new { controller = “User”, action = “GetUser”, id = UrlParameter.Optional }

Step 6 − Run the application which will look like the following screenshot.

If you select Admin from the dropdown, it will go and fetch all the users with Admin type. This is happening via AJAX and does not reload the entire page.

jQuery ajax() Method

Example

Change the text of a

element using an AJAX request:

$.ajax({url: “demo_test.txt”, success: function(result){

$(“#div1”).html(result);

}});

});

Using Ajax in Asp.Net MVC

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”; }

Ajax calls to .Net5 MVC Controllers (using JQuery)
Ajax calls to .Net5 MVC Controllers (using JQuery)

The ASP File – “gethint.asp”

The ASP file checks an array of names, and returns the corresponding name(s) to the browser:

response.expires=-1

dim a(30)

‘Fill up array with names

a(1)=”Anna”

a(2)=”Brittany”

a(3)=”Cinderella”

a(4)=”Diana”

a(5)=”Eva”

a(6)=”Fiona”

a(7)=”Gunda”

a(8)=”Hege”

a(9)=”Inga”

a(10)=”Johanna”

a(11)=”Kitty”

a(12)=”Linda”

a(13)=”Nina”

a(14)=”Ophelia”

a(15)=”Petunia”

a(16)=”Amanda”

a(17)=”Raquel”

a(18)=”Cindy”

a(19)=”Doris”

a(20)=”Eve”

a(21)=”Evita”

a(22)=”Sunniva”

a(23)=”Tove”

a(24)=”Unni”

a(25)=”Violet”

a(26)=”Liza”

a(27)=”Elizabeth”

a(28)=”Ellen”

a(29)=”Wenche”

a(30)=”Vicky”

‘get the q parameter from URL

q=ucase(request.querystring(“q”))

‘lookup all hints from array if length of q>0

if len(q)>0 then

hint=””

for i=1 to 30

if q=ucase(mid(a(i),1,len(q))) then

if hint=”” then

hint=a(i)

else

hint=hint & ” , ” & a(i)

end if

end if

next

end if

‘Output “no suggestion” if no hint were found

‘or output the correct values

if hint=”” then

response.write(“no suggestion”)

else

response.write(hint)

end if

%>

AJAX can be used for interactive communication with a database.

Disadvantages of AJAX in ASP.net

Let us discuss some disadvantages of AJAX in ASP.net. Some of these disadvantages of AJAX in ASP.net are described below –

  • The size of a data request is largely increased as all these data requests are URL encoded.
  • It highly depends on JavaScript as it is a JavaScript built-in. Therefore, if a user disables JavaScript in the browser, then AJAX stops working.
  • Indexing of an AJAX application cannot be done using Google-like search engines.
  • Since all the files are downloaded on the client-side in an AJAX application, security is scarce in these applications.
  • Within the AJAX, the server information is completely inaccessible.
.NET Core MVC CRUD  using .NET Core Web API and ajax call | Consume secured  .NET Core API in MVC
.NET Core MVC CRUD using .NET Core Web API and ajax call | Consume secured .NET Core API in MVC

What is AJAX?

AJAX = Asynchronous JavaScript and XML.

AJAX is a technique for creating fast and dynamic web pages.

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.

Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

Sử dụng jQuery Ajax trong ASP.NET MVC

Sử dụng jQuery Ajax trong ASP.NET MVC

Trong bài viết này hướng dẫn sử dụng jQuery ajax với các phương thức Action sử dụng http verbs tương ứng.

Địa chỉ URL trong jQuery Ajax
  • Được sử dụng truy cập thông qua trình duyệt url
  • Được sử dụng để gọi trong JQuery ajax


public JsonResult UrlResponse() //truy cập sử dụng Url { return Json(new { Name = "UrlResponse", Response = "Response from Get", Date = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") }, JsonRequestBehavior.AllowGet); }

Loại giao thức trong jQuery Ajax
  • Có thể chỉ sử dụng cho gọi thông qua Ajax.
  • Nếu sử dụng trình duyệt truy cập sẽ tạo ra lỗi.


[HttpGet] public JsonResult TypedResponse() //Lỗi nếu truy cập sử dụng Url { return Json(new { Name = "TypedResponse", Response = "Response from Get", Date = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") }, JsonRequestBehavior.AllowGet); }

Bây giờ chúng ta sẽ bắt đầu sử dụng phương thức action trong MVC, và sử dụng JQuery Ajax gọi $.ajax.
Một số thành phần trong cách gọi ajax

1. Xác định phương thức action trong MVC được gọi trong Ajax.Thuộc tính url trong $.ajax xác định controller và action trong MVC, theo định dạng /{controller}/{action}

Ví dụ:


url: ‘/User/Create’ url: ‘/User/Get/20’

Hoặc có thể sử dụng phương thức Url.Action để xác định controller và action.


url: ‘@Url.Action(“User”,”Create”)’

2. Xác định http verb sử dụng trong Ajax.Thuộc tính type với các giá trị ‘GET/ POST/ PUT/ DELETE’ sử dụng trong Ajax tương ứng với HttpVerbs trong phương thức action MVC.

Ví dụ:

Type : “POST”

3. Xác định tham số nếu phương thức action trong MVC có sử dụng tham số.

Thuộc tính data xác định dữ liệu được truyền cho tham số trong phương thức action.

Ví dụ:


data: JSON.stringify({ user: { name: ‘Rintu’, email: ‘[email protected]’ } }), data: { name: ‘Rintu’, email: ‘[email protected]’ },

4. Nhận dữ liệu trả về sau khi thực hiện thành công.

Thuộc tính success xác định hàm nhận dữ liệu trả về.

Ví dụ:


success: function (data) { alert(data); },

5. Nếu xảy ra lỗi, thuộc tính error xác định hàm nhận lỗi trả về.

Ví dụ:


error: function (xhr) { alert(‘error’); }

Truyền tham số cơ bản từ jQuery ajax đến phương thức action MVC

Trong UserController MVC chứa phương thức action:


[HttpGet] public JsonResult Get(int id) { return Json("Response from Get", JsonRequestBehavior.AllowGet); }

Cách gọi phương thức action Get trong ajax:


$.ajax({ url: '@Url.Action(“User”,”Get”), dataType: "json", type: "GET", contentType: 'application/json; charset=utf-8', data: {id:1}, async: true, processData: false, cache: false, success: function (data) { alert(data); }, error: function (xhr) { alert('error'); } });

Truyền tham số là đối tượng json từ jQuery ajax đến phương thức action MVC

Phương thức action Create trong UserController nhận đối tượng user làm tham số.


// POST: /User/Create [HttpPost] public JsonResult Create(User user) { return Json("Response from Create"); }

Cách gọi trong jQuery ajax.

Tạo dữ liệu kiểu json trong ajax để truyền cho phương thức Create trong MVC.


/*POST*/ $.ajax({ url: '@Url("User","Create"), dataType: "json", type: "POST", contentType: 'application/json; charset=utf-8', data: JSON.stringify({ user: { name: 'Rintu', email: '[email protected]' } }), async: true, processData: false, cache: false, success: function (data) { alert(data); }, error: function (xhr) { alert('error'); } })

Truyền tham số phức hợp từ jQuery ajax đến phương thức action MVC

Phương thức action Edit trong UserController nhận 2 tham sô: id và đối tượng user.


[HttpPost] public JsonResult Edit(int id, User user) { return Json("Response from Edit"); }

Cách gọi phương thức action Edit trong jQuery ajax.


$.ajax({ url: '/User/Edit', dataType: "json", type: "POST", contentType: 'application/json; charset=utf-8', data: JSON.stringify({ id: 100, user: {name: 'Rintu', email: '[email protected]'} }), async: true, processData: false, cache: false, success: function (data) { alert(data); }, error: function (xhr) { alert('error'); } });


Bạn đang muốn tìm kiếm 1 công việc với mức thu nhập cao.

✅ Hoặc là bạn đang muốn chuyển đổi công việc mà chưa biết theo học ngành nghề gì cho tốt.✅ Giới thiệu với bạn Chương trình đào tạo nhân sự dài hạn trong 12 tháng với những điều đặc biệt mà chỉ có tại IMIC và đây cũng chính là sự lựa chọn phù hợp nhất dành cho bạn:👉 Thứ nhất: Học viên được đào tạo bài bản kỹ năng, kiến thức chuyên môn lý thuyết, thực hành, thực chiến nhiều dự án và chia sẻ những kinh nghiệm thực tế từ Chuyên gia có nhiều năm kinh nghiệm dự án cũng như tâm huyết truyền nghề.👉 Thứ hai: Được ký hợp đồng cam kết chất lượng đào tạo cũng như mức lương sau tốt nghiệp và đi làm tại các đối tác tuyển dụng của IMIC. Trả lại học phí nếu không đúng những gì đã ký kết.👉 Thứ ba: Cam kết hỗ trợ giới thiệu công việc sang đối tác tuyển dụng trong vòng 10 năm liên tục.👉 Thứ tư: Được hỗ trợ tài chính với mức lãi suất 0 đồng qua ngân hàng VIB Bank.👉 Có 4 Chương trình đào tạo nhân sự dài hạn dành cho bạn lựa chọn theo học. Gồm có:1) Data Scientist full-stack2) Embedded System & IoT development full-stack3) Game development full-stack4) Web development full-stack✅ Cảm ơn bạn đã dành thời gian lắng nghe những chia sẻ của mình. Và tuyệt vời hơn nữa nếu IMIC được góp phần vào sự thành công của bạn.✅ Hãy liên hệ ngay với Phòng tư vấn tuyển sinh để được hỗ trợ về thủ tục nhập học.✅ Chúc bạn luôn có nhiều sức khỏe và thành công!

I’m trying to get started with ASP.NET MVC Ajax calls.

Controller:


public class AjaxTestController : Controller { // // GET: /AjaxTest/ public ActionResult Index() { return View(); } public ActionResult FirstAjax() { return Json("chamara", JsonRequestBehavior.AllowGet); } }

View:

<br /> FirstAjax<br />

I just need to print an alert with the controller method returning data. Above code just print “chamara” on my view. An alert is not firing.

UPDATE

I modified my controller as below and it start working. I don’t have an clear idea why it’s working now. Some one please explain. The parameter “a” does not related i added it because i can not add two methods with same method name and parameters.I think this might not be the solution but its working


public class AjaxTestController : Controller { // // GET: /AjaxTest/ [HttpGet] public ActionResult FirstAjax() { return View(); } [HttpPost] public ActionResult FirstAjax(string a) { return Json("chamara", JsonRequestBehavior.AllowGet); } }

Ajax methodology in web development can or cannot have input query parameters for processing/loading web parts on the web page. However, complex logic and improved performance measures demand Ajax call to pass multiple input query parameters whether in a typical multiple parameter format or JSON input format.

Today, I shall be demonstrating the integration of Ajax calls by passing multiple input query parameters with the ASP.NET MVC5 platform.

Prerequisites

The following are some prerequisites before you proceed any further in this tutorial,

  1. Knowledge of Jquery.
  2. Knowledge of HTML.
  3. Knowledge of JavaScript.
  4. Knowledge of Bootstrap.
  5. Knowledge of ASP.NET MVC5.
  6. Knowledge of C# Programming.

The example code is being developed in Microsoft Visual Studio 2019 Professional.

Let’s begin now.

Step 1

Create a new MVC web project and name it “MVCAjaxWithParam”.

Step 2

Create a “Controllerss\HomeController.cs” file with default Index method and GetData(…) method with two input query parameters for Ajax call with following lines of code i.e.

  1. public ActionResult GetData(int customerID, string fname = “”)
  2. JsonResult result = new JsonResult();
  3. DataTable data = DataTable();
  4. result = this.Json(JsonConvert.SerializeObject(data), JsonRequestBehavior.AllowGet);
  5. return result;

In the above code, I have created a simple “GetData(…)” method with ActionResult returning type for client-side ajax calling to return result data in JSON format. I have first loaded my data in DataTable structure, then I have applied the input query filter with OR condition and finally, I have prepared my JSON response.

Step 3

Now, create the subsequent view “Views\Home\Index.cshtml”of “Controllerss\HomeController.cs” index method and add table HTML tag as shown below i.e.

  1. id=”TableId”
  2. cellspacing=”0″
  3. align=”center”
  4. width=”100%”>

In the above code, I have created a simple responsive Bootstrap style HTML table tag structure. I will populate the data in this table using Ajax call.

Step 4

Now, create the JavaScript file “Scripts\script-custom-ajax.js” with the following lines of code i.e.

  1. $(document).ready(function ()
  2. var customerID = 23;
  3. var firstname = “John”;
  4. $.ajax(
  5. type: ‘POST’,
  6. dataType: ‘JSON’,
  7. url: ‘/Home/GetData’,
  8. data: { customerID: customerID, fname: firstname },
  9. success:
  10. function (response)
  11. convertJsonToHtmlTable(JSON.parse(response), $(“#TableId”));
  12. },
  13. error:
  14. function (response)
  15. alert(“Error: ” + response);
  16. });
  17. });

In the above code, I have made an Ajax call to my server-side at the load of the page to get input query base filter data, since I am now passing multiple query parameters to the Ajax call. After receiving the processed JSON data from the server-side you can utilize any logic of your own to convert the JSON data to HTML table.

Step 5

Now, execute the provided solution and you will be able to see the following in action i.e.

When I only pass single “CustomerID” input query parameter then I will get the following result as shown below i.e.:

FULL MATCH: Frederic CAUDRON - GO Do-young | PBA R32 - Silkroad & Ansan PBA Championship 23-24
FULL MATCH: Frederic CAUDRON – GO Do-young | PBA R32 – Silkroad & Ansan PBA Championship 23-24

Conclusion

In this article, you will learn integration of Ajax calls by passing multiple input query parameters with ASP.NET MVC5 platform. You will also learn to create a server-side method, which will be called by client-side Ajax call using Jquery. You will learn to make simple client-side Ajax calls at the load of the page and finally, you will learn to pass multiple input query parameters to the Ajax call.

  • MVC Framework Tutorial
  • MVC Framework – Home
  • MVC Framework – Introduction
  • MVC Framework – Architecture
  • MVC Framework – ASP.NET Forms
  • MVC Framework – First Application
  • MVC Framework – Folders
  • MVC Framework – Models
  • MVC Framework – Controllers
  • MVC Framework – Views
  • MVC Framework – Layouts
  • MVC Framework – Routing Engine
  • MVC Framework – Action Filters
  • Advanced Example
  • MVC Framework – Ajax Support
  • MVC Framework – Bundling
  • Exception Handling
  • MVC Framework Useful Resources
  • Questions & Answers
  • MVC Framework – Quick Guide
  • MVC Framework – Resources
  • MVC Framework – Discussion

MVC Framework – Ajax Support

As you might be knowing, Ajax is a shorthand for Asynchronous JavaScript and XML. The MVC Framework contains built-in support for unobtrusive Ajax. You can use the helper methods to define your Ajax features without adding a code throughout all the views. This feature in MVC is based on the jQuery features.

To enable the unobtrusive AJAX support in the MVC application, open the Web.Config file and set the UnobtrusiveJavaScriptEnabled property inside the appSettings section using the following code. If the key is already present in your application, you can ignore this step.

After this, open the common layout file _Layout.cshtml file located under Views/Shared folder. We will add references to the jQuery libraries here using the following code −

Get User

@Html.Action(“GetUserData”, new {selectedRole = Model })
First Last Role

@using (Ajax.BeginForm(“GetUser”, ajaxOpts)) {

@Html.DropDownList(“selectedRole”, new SelectList( new [] {“All”}.Concat(Enum.GetNames(typeof(Role)))))

}

Step 5 − Finally, change the Route.config entries to launch the User Controller.

defaults: new { controller = “User”, action = “GetUser”, id = UrlParameter.Optional }

Step 6 − Run the application which will look like the following screenshot.

If you select Admin from the dropdown, it will go and fetch all the users with Admin type. This is happening via AJAX and does not reload the entire page.

In this article I will explain with an example, how to use jQuery AJAX and JSON in ASP.Net MVC 5 Razor.
The Controller action method will be called using jQuery AJAX and JSON from View in ASP.Net MVC 5 Razor.

Model

Following is a Model class named PersonModel with two properties i.e. Name and DateTime.

public class PersonModel

///

/// Gets or sets Name.

///

public string Name { get; set; }

///

/// Gets or sets DateTime.

///

public string DateTime { get; set; }

Controller

The Controller consists of two Action methods.

Action method for handling GET operation

Inside this Action method, simply the View is returned.

Action method for handling jQuery AJAX operation

This Action method handles the call made from the jQuery AJAX function from the View.

Note: The following Action method handles AJAX calls and hence the return type is set to JsonResult.

The value of the name parameter is assigned to the Name property of the PersonModel object along with the Current DateTime and finally the PersonModel object is returned back as JSON to the jQuery AJAX function.

public class HomeController : Controller

// GET: Home

public ActionResult Index()

return View();

[HttpPost]

public JsonResult AjaxMethod(string name)

PersonModel person = new PersonModel

Name = name,

DateTime = DateTime.Now.ToString()

};

return Json(person);

View

Next step is to add a View for the Controller and while adding you will need to select the PersonModel class created earlier.

Inside the View, in the very first line the PersonModel class is declared as Model for the View. The View consists of an HTML TextBox element and a Button. The Button has been assigned a jQuery click event handler and when the Button is clicked a jQuery AJAX called is made to the Controller’s action method.

The following figure describes a jQuery AJAX call in ASP.Net MVC

The URL for the jQuery AJAX call is set to the Controller’s action method i.e. /Home/AjaxMethod. The value of the TextBox is passed as parameter and the returned response is displayed using JavaScript Alert Message Box.

@model jQuery_AJAX_MVC.Models.PersonModel

@{

Layout = null;

<br /> Index<br />

Screenshot

Downloads

This article gives you details about how you can implement jQuery AJAX calls to ASP.NET MVC controller and display JSONResult on view.

For this tutorial, we will use the Northwind database. If you do not have Northwind database you can download from here.

You will have a DropDownList filled with Northwind.Categories table. You may check for ways to bind MVC DropDownList. On selection change of this DropDownList, a jQuery Ajax call will be made to the controller. The controller will return JSONResult and success part of ajax call will display JSONResult.

Follow the below steps to implement jQuery AJAX call to MVC Controller and display JSON result.

Open your Visual Studio and create a empty ASP.NET MVC application.

Click on File -> New Project -> Web -> ASP.NET web application.

From the next window Select template Empty and from Add folders and core reference choose MVC.

Name it as AJAXCalls and click Ok. For more details check Getting Started with ASP.NET MVC.

We will use a model class to represet the Product entity.

Right click on Models folder and select Add -> Class name it as Product -> click Ok.

Add below properties for the Product model.


namespace AJAXCalls.Models { public class Product { public string ProductID { get; set; } public string ProductName { get; set; } public string QuantityPerUnit { get; set; } public string UnitPrice { get; set; } public string UnitsInStock { get; set; } public string ReorderLevel { get; set; } } }

For detail description see ASP.NET MVC model example.

In this step, you will add a simple controller. Right click on the Controllers folder and select Add -> Controller.

From Add Scaffold window select MVC 5 Controller – Empty and click Add.

Name it as HomeController.

Open HomeController from the Controllers folder and add Action method with name ShowCategoryProducts. For more details about Action method ASP.NET MVC Controller Action Method and Action Result.

Add the below code to ShowCategoryProducts


public ActionResult ShowCategoryProducts() { List

items = new List

(); items.Add(new SelectListItem { Text = "Select Category", Value = "0", Selected = true }); items.Add(new SelectListItem { Text = "Beverages", Value = "1" }); items.Add(new SelectListItem { Text = "Condiments", Value = "2" }); items.Add(new SelectListItem { Text = "Confections", Value = "3" }); items.Add(new SelectListItem { Text = "Dairy Products", Value = "4" }); items.Add(new SelectListItem { Text = "Grains/Cereals", Value = "5" }); items.Add(new SelectListItem { Text = "Meat/Poultry", Value = "6" }); items.Add(new SelectListItem { Text = "Produce", Value = "7" }); items.Add(new SelectListItem { Text = "Seafood", Value = "8" }); ViewBag.CategoryType = items; return View(); }


It adds Category details to ViewBag property. These property values will be shown in Category Type DropDownList.

In this step, you will add an MVC View to display Category and Product details.

Open HomeController from Controllers folder -> Go to ShowCategoryProducts action method -> right click and select Add View

It adds a View under Views -> Home folder with the name ShowCategoryProducts.cshmtl.

Now add a DropDownList to display Categories and empty Table to show products depending on the selected category.

Add below html to ShowCategoryProducts.cshtml


@{ ViewBag.Title = "jQuery Ajax Call example in ASP.NET MVC - dotnetmentors.com"; }

jQuery Ajax Call example in ASP.NET MVC - dotnetmentors.com

@using (Html.BeginForm("CategoryChosen", "Home", FormMethod.Get)) {

Category Type : @Html.DropDownList("CategoryType")
ProductID ProductName QuantityPerUnit UnitPrice UnitsInStock ReorderLevel

}

Open HomeController and action method which accepts Category ID as an input parameter, create a list of products whose CategoryID is equal to input parameter and return it as JSON result.

If you have data in the DataTable or Dataset you can convert datatable to JSON string.

Add below Action method to HomeController


public JsonResult GetProducts(string id) { List products = new List (); string query = string.Format("SELECT [ProductID], [ProductName], [QuantityPerUnit],[UnitPrice],[UnitsInStock],[ReorderLevel] " + " FROM [Northwind].[dbo].[Products] WHERE CategoryID = {0}",id); using (SqlConnection con = new SqlConnection("your connection string")) { using (SqlCommand cmd = new SqlCommand(query, con)) { con.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { products.Add( new Product { ProductID = reader.GetValue(0).ToString(), ProductName = reader.GetString(1), QuantityPerUnit = reader.GetString(2), UnitPrice = reader.GetValue(3).ToString(), UnitsInStock = reader.GetValue(4).ToString(), ReorderLevel = reader.GetValue(5).ToString() } ); } } } return Json(products, JsonRequestBehavior.AllowGet); }

It creates a list of Products model and returns as JSON.

In this step, you will add code for CategoryType DropDownList change event. This will create the AJAX helper to call the MVC controller action method.

Below is the code which fires on change of DropDownList, create an AJAX call with required details, makes a call to GetProducts controller action method, accepts JSON result, and display as a Table object.

Add it after of the above code which you added in step 4.

On success it displays the JSON string returned by action method, manipulate it and display product details on View.

Execute your application and browse to http://localhost: /home/ShowCategoryProducts.

Select any value from CategoryType DropDownList. It makes an AJAX call to fill Products table. It display below screen.

ASP AJAX

AJAX is about updating parts of a web page, without reloading the whole page.

Asp.net Ajax Json Crud
Asp.net Ajax Json Crud

Conclusion

AJAX is used to create dynamic web pages that do not require page reloading when any part of the whole web page content or the whole web page content is changed. The server data exchange is asynchronous in nature and AJAX in ASP.net uses multiple technologies like XSLT, XHTML, CSS, JavaScript, etc.

To master and learn more about AJAX in ASP.net and all its related technologies properly and well versed to get into full-stack development, one might consider referring and learning in-depth from various resources, study materials, and course books.

If you are interested in understanding and acquiring knowledge on AJAX in ASP.net and all its related technologies in order to become a full-stack web and desktop application developer, Simplilearn offers an exclusive full-stack web development certification course to master both backend and frontend with tools, like SpringBoot, AngularMVC, JSPs, and Hibernate to start your career as a full-stack developer.

If you are not up to enrolling yourself into the full certification course yet, Simplilearn also offers free online skill-up courses in several domains, from data science and business analytics to software development, AI, and machine learning. Become a full-stack web developer today!

If you have any queries leave them in the comments section of this article and our experts will get back to you on the same, ASAP!

jQuery AJAX method is a very powerful function for doing asynchronous operations from the Web pages. It helps to update parts of a Web page without reloading the whole page. This increases the Website’s speed and reduces the load. It can be used with any Web technology like HTML, ASP.NET, ASP.NET MVC, PHP, Ruby or any other.

With jQuery AJAX method, you can create high performance features in our Website. Let me show you how to use this method in ASP.NET MVC page.

ASP.NET MVC Page

To understand the working of jQuery AJAX, I will create a login feature in ASP.NET MVC page. The page will have 2 input controls to enter the username and the password. There will also be a button to submit the two values for checking from the database.

When the username and password are correct, the secured information of the user is shown, else the “wrong username and password” is shown.

The main attraction here is that I will use jQuery AJAX method to check the username and the password. There will be no page reloading during checking.

To start learning jQuery AJAX method, I would suggest you check – jQuery AJAX. Also, look for the syntax and the key-value pairs that can be passed to this method.

The Controller Code

Start with creating a “Controller” in your ASP.NET MVC Application. Now, add a C# function “GetSecuredData” into the controller.


[HttpPost]
public string GetSecuredData(string userName, string password)
{
string securedInfo = "";
if ((userName == "admin") && (password == "admin"))
securedInfo = "Hello admin, your secured information is .......";
else
securedInfo = "Wrong username or password, please retry.";
return securedInfo;
}

Explanation

The C# function given above will be called by jQuery AJAX method. As you can see, this function has 2 parameters, “username” and “password”. In these 2 parameters, it receives the username and the password values. It then checks them and shows the secured information, if they are the correct ones.

You can also change the code given above to include the database operation, where the username and the password are checked against the ones stored in the database.

The View code

Now, create a view for the Controller. This view will contain the two input controls for the username and password. There will be a button, which when clicked will call jQuery AJAX function.

Enter the Username and Password:

(enter "admin" for both username and password)


Explanation

The button click event will call jQuery AJAX event. We pass the “controller name/function name” to the URL field. The jQuery AJAX event will call the C# function which gets the username and password values in its parameters.

Finally, in the success function we will show the returned value from the C# function.

That’s all for the code, isn’t it really simple?

Conclusion

I hope, you like this article on jQuery AJAX usage in ASP.NET MVC. Please share your feedback.

Check my other tutorial on C-Sharpcorner – Delete records from GridView without Page Reload using jQuery

Server to Client

In ASP.net MVC, we add code in the Controller action. The Controller here is the Student and the action name here is GetStudList which takes a list of students as parameters.

Code Snippet

public List

GetStudList()

var studList = new List

()

new Student { ID=1, Name=”Dina”},

new Student { ID=2, Name=”Chester”}

};

return studList;

Following this, to get the list of Students, you need to send a request to the Server. To do so-

  1. You need to load the jQuery library. To enable this, you are going to add a jQuery CDN (Content Delivery Network) reference.
  2. To get a list of students from the Server, you have to write and execute a code block and then display it.

Code Snippet

In the above code snippet, “GET” is the method type that gets data as a response parameter in the success properties. This method does the following – loops over the student list collects student data and binds the whole as a div.

In order to display the loader icon when the AJAX request is being sent to the Server and when the AJAX completes, the loader icon is hidden.

The following code does the job –

Introduction to ASP.NET Core MVC (.NET 8)
Introduction to ASP.NET Core MVC (.NET 8)

Create an Unobtrusive Ajax Application

In the example that follows, we will create a form which will display the list of users in the system. We will place a dropdown having three options: Admin, Normal, and Guest. When you will select one of these values, it will display the list of users belonging to this category using unobtrusive AJAX setup.

Step 1 − Create a Model file Model.cs and copy the following code.

using System; namespace MVCAjaxSupportExample.Models { public class User { public int UserId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime BirthDate { get; set; } public Role Role { get; set; } } public enum Role { Admin, Normal, Guest } }

Step 2 − Create a Controller file named UserController.cs and create two action methods inside that using the following code.

using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using MVCAjaxSupportExample.Models; namespace MVCAjaxSupportExample.Controllers { public class UserController : Controller { private readonly User[] userData = { new User {FirstName = “Edy”, LastName = “Clooney”, Role = Role.Admin}, new User {FirstName = “David”, LastName = “Sanderson”, Role = Role.Admin}, new User {FirstName = “Pandy”, LastName = “Griffyth”, Role = Role.Normal}, new User {FirstName = “Joe”, LastName = “Gubbins”, Role = Role.Normal}, new User {FirstName = “Mike”, LastName = “Smith”, Role = Role.Guest} }; public ActionResult Index() { return View(userData); } public PartialViewResult GetUserData(string selectedRole = “All”) { IEnumerable data = userData; if (selectedRole != “All”) { var selected = (Role) Enum.Parse(typeof (Role), selectedRole); data = userData.Where(p => p.Role == selected); } return PartialView(data); } public ActionResult GetUser(string selectedRole = “All”) { return View((object) selectedRole); } } }

Step 3 − Now create a partial View named GetUserData with the following code. This view will be used to render list of users based on the selected role from the dropdown.

@model IEnumerable

@foreach (var item in Model) {

}

@Html.DisplayNameFor(model => model.FirstName) @Html.DisplayNameFor(model => model.LastName) @Html.DisplayNameFor(model => model.BirthDate)
@Html.DisplayFor(modelItem => item.FirstName) @Html.DisplayFor(modelItem => item.LastName) @Html.DisplayFor(modelItem => item.BirthDate)

Step 4 − Now create a View GetUser with the following code. This view will asynchronously get the data from the previously created controller’s GetUserData Action.

@using MVCAjaxSupportExample.Models @model string @{ ViewBag.Title = “GetUser”; AjaxOptions ajaxOpts = new AjaxOptions { UpdateTargetId = “tableBody” }; }

Example Explained

In the example above, when a user types a character in the input field, a function called “showHint()” is executed.

The function is triggered by the onkeyup event.

Here is the HTML code:

Example


Start typing a name in the input field below:

First name:

Suggestions:

Code explanation:

First, check if the input field is empty (str.length == 0). If it is, clear the content of the txtHint placeholder and exit the function.

However, if the input field is not empty, do the following:

  • Create an XMLHttpRequest object
  • Create the function to be executed when the server response is ready
  • Send the request off to an ASP file (gethint.asp) on the server
  • Notice that q parameter is added gethint.asp?q=”+str
  • The str variable holds the content of the input field
ASP.NET Web API CRUD using jQuery Ajax Single Page Application | ASP.NET Web API 🔥
ASP.NET Web API CRUD using jQuery Ajax Single Page Application | ASP.NET Web API 🔥

Benefits of Ajax

  • Callbacks
  • Making Asynchronous Calls
  • User-Friendly
  • Improve the speed, performance and usability of a web application

Implementation of Ajax can be done in two way in ASP.Net Application

  • using Update Panel and,
  • using jQuery

What Advances have Been Made to Ajax?

JavaScript is the client-side scripting language and XML is a mark-up language to define data. And we have, JSON(JavaScript Object Notation) as another mark-up language to define data as well. JSON is much easier to use with JavaScript than XML. After the combination of JavaScript and Ajax, the XML Web Services are being replaced by JSON Web Services.

Another major advance to JavaScript and Ajax is the JavaScript object library called jQuery, which is the free, open-source software. It is a wrapper for JavaScript. jQuery is used to write the JavaScript to navigate and manipulate a page and make asynchronous Ajax callbacks.

Hence, Ajax callbacks have become standard programming practices by using jQuery and JSON Web Services for designing and developing web applications.

Syntax

The parameters specifies one or more name/value pairs for the AJAX request.

Possible names/values in the table below:

Name Value/Description
async A Boolean value indicating whether the request should be handled asynchronous or not. Default is true
beforeSend(xhr) A function to run before the request is sent
cache A Boolean value indicating whether the browser should cache the requested pages. Default is true
complete(xhr,status) A function to run when the request is finished (after success and error functions)
contentType The content type used when sending data to the server. Default is: “application/x-www-form-urlencoded”
context Specifies the “this” value for all AJAX related callback functions
data Specifies data to be sent to the server
dataFilter(data,type) A function used to handle the raw response data of the XMLHttpRequest
dataType The data type expected of the server response.
error(xhr,status,error) A function to run if the request fails.
global A Boolean value specifying whether or not to trigger global AJAX event handles for the request. Default is true
ifModified A Boolean value specifying whether a request is only successful if the response has changed since the last request. Default is: false.
jsonp A string overriding the callback function in a jsonp request
jsonpCallback Specifies a name for the callback function in a jsonp request
password Specifies a password to be used in an HTTP access authentication request.
processData A Boolean value specifying whether or not data sent with the request should be transformed into a query string. Default is true
scriptCharset Specifies the charset for the request
success(result,status,xhr) A function to be run when the request succeeds
timeout The local timeout (in milliseconds) for the request
traditional A Boolean value specifying whether or not to use the traditional style of param serialization
type Specifies the type of request. (GET or POST)
url Specifies the URL to send the request to. Default is the current page
username Specifies a username to be used in an HTTP access authentication request
xhr A function used for creating the XMLHttpRequest object
Asp.Net Mvc Ajax Crud Part 1
Asp.Net Mvc Ajax Crud Part 1

Example Explained – The HTML Page

When a user selects a customer in the dropdown list above, a function called “showCustomer()” is executed. The function is triggered by the “onchange” event:

Customer info will be listed here…

Source code explanation:

If no customer is selected (str.length==0), the function clears the content of the txtHint placeholder and exits the function.

If a customer is selected, the showCustomer() function executes the following:

  • Create an XMLHttpRequest object
  • Create the function to be executed when the server response is ready
  • Send the request off to a file on the server
  • Notice that a parameter (q) is added to the URL (with the content of the dropdown list)

Advantages of AJAX in ASP.net

You will explore some advantages of AJAX in ASP.net. Some of these advantages of AJAX in ASP.net are described below –

  • Ajax in ASP.net improves the responsiveness and interactivity of a website.
  • Ajax in ASP.net helps in reducing the traffic between server and client.
  • Ajax in ASP.net reduces the cross-browser issues as it is cross-browser friendly.
  • In Ajax in ASP.net, you can use a single web page or SPA to be able to handle several features and apply multi-purpose applications to it.
  • In Ajax in ASP.net, you can use APIs or Application Programming Interfaces and because these work seamlessly with JavaScript and HTTP methods, it makes it an enormous advantage to building dynamic web applications.
ASP.NET Core MVC 6.0 Full Course (Beginner)
ASP.NET Core MVC 6.0 Full Course (Beginner)

What is Ajax?

As we all know, AJAX means Asynchronous JavaScript and XML. It is a client-side script that communicates to and from a server/database without the need for a postback or a complete page refresh. The Ajax speeds up response time.

In other words, Ajax is the method of exchanging data with a server, and updating parts of a web page, without reloading the entire page.

Ajax Call Getting started

@{ ViewBag.Title = “Home Page”; }

ASP.NET Core MVC 6.0 Full Course ( Giỏ hàng, Tìm kiếm nâng cao, Phân trang...)
ASP.NET Core MVC 6.0 Full Course ( Giỏ hàng, Tìm kiếm nâng cao, Phân trang…)

Client to Server

To send data from Server to Client using AJAX in ASP.net. Let us see how to do the same from Client to Server using AJAX in ASP.net.

To save the list of students to the database, you have to send these lists of students to the Server. To do so, you need to add the following code to the Controller’s action. The Controller is Student and the action name is SaveStudList that takes in the parameter – list of Students.

Code Snippet

public static bool SaveStudList(List

studList)

try

// block of statements to save student list to database

catch (Exception ex)

// if logging error arises

return false;

return true;

To send complex objects converted to a list of students to the Server, you have to create an array and then push a JSON object into it. Following this, using the JSON.stringify( ) method, you have to convert this array into JSON string in order to effectively send the data.

Through this, using $.Ajax, you can implement AJAX in jQuery.

AJAX is Based on Internet Standards

AJAX is based on internet standards, and uses a combination of:

  • XMLHttpRequest object (to exchange data asynchronously with a server)
  • JavaScript/DOM (to display/interact with the information)
  • CSS (to style the data)
  • XML (often used as the format for transferring data)

AJAX applications are browser- and platform-independent!

Autocomplete Textbox In MVC | With Database | Jquery Ajax
Autocomplete Textbox In MVC | With Database | Jquery Ajax

Demonstration: Implementation of Ajax using jQuery

Step 1

Create a new Project and choose ASP.NET MVC web application.

Step 2

Just Ignore the built-in Models and Controllers and make your own model.

Here I am creating a model called “Students” having properties studentID, studentName and studentAddress as shown below,


public class Student
{
[Key]
public int studentID { get; set; }
[Required]
public string studentName { get; set; }
[Required]
public string studentAddress { get; set; }
}

Add “using System.ComponentModel.DataAnnotations;” Attributes to Validate Model Data and then build the project once.

Step 3

Let’s create another model by inheriting the DbContext. It is a class that manages all the database operations, like database connection, and manages various entities of the Entity Model.

We can also say DbContext is a wrapper of ObjectContext. So, DbContext is a lightweight version of the ObjectContext and is exposes only the common features that are really required in programming.

Here I am creating a model called “StudentContext” as shown below,


public class StudentContext : DbContext
{
public DbSet

Students { get; set; }
}

Add “using System.Data.Entity;” that provides access to the core functionality of the entity framework.

Step 4

Now create a controller to written the code for inserting data into database, displaying data into view.

Here I am creating “Student” controller. Inside the Controller, I am creating an object of StudentContext for inserting and retrieving data from database. Also add the necessary namespace.


StudentContext context = new StudentContext();

Step 5

Now I’m creating the action methods for Inserting and retrieving the data to/from the database.

Here I am creating an [HttpPost] action method “createStudent” for inserting the JSON-Formatted data to database. I am Using [HttpPost] attribute to Save/Post the data as below:


[HttpPost]
public ActionResult createStudent(Student std)
{
context.Students.Add(std);
context.SaveChanges();
string message = "SUCCESS";
return Json(new { Message = message, JsonRequestBehavior.AllowGet });
}

Similarly, I am also creating JSON method “getStudent” to retrieve data from database and returning raw JSON data to be consumed by JavaScript in view as shown below,


public JsonResult getStudent(string id)
{
List

students = new List

();
students = context.Students.ToList();
return Json(students, JsonRequestBehavior.AllowGet);
}


Step 6

Now add a view to display the data and data inserting field. Here, I am adding a view named “Index.cshtml”. Then, write the HTML codes for making the data input field, submit button and also for displaying the data in same page. You can use bootstrap classes for designing. Here I am using bootstrap. My designing code is as below:

Please enter the details below.

ID Student Name Student Address

We can simply use the bootstrap class and call jQuery functions in ASP.NET MVC because during the project creation it will by default added to project and also linked to the template.

Step 7

Now I will write the script for inserting the data as well as retrieving and displaying it to the view. Just after the HTML code finished add the script shown below,


@section Scripts
{

}

We are using Ajax to refresh “tblStudent” so it refreshes only the particular table, rather than refreshing entire page. After clicking the “submitButton” the data from the input fields are taken in variable and redirected to action “createStudent” of “StudentController” to insert into the database. And, I have written a function “LoadData” to display the data from database to view continuously after inserting data. Inside “LoadData” function I am calling “getStudent” method which returns result in JSON and the JSON-Formatted data are presented in html by the underlying statements.

Step 8

Now, configure the Database connectionStrings in “web.config” file of the particular project as shown below,

In the above connectingString “StudentContext” is the name of class inherited from abstract Class “DbContext” in “StudentContext.cs” file. “RAVI-KANDEL” is the name of the Database Server and “Student” is the name of the Database. Change “RAVI-KANDEL” with your Database Server name. Finally, run your application and navigate to Student controller. Also you can configure “RouteConfig.cs” and set the controller to “Student” for direct navigation to the Student controller when loading the application.

You can add the records and can see added data in the table after the form-control as shown below,

Also, you can open the database server and see the data stored in database over there.

Please feel free to comment/feedback.

Happy Coding!

Keywords searched by users: ajax syntax in mvc

Asp.Net Mvc Interview Question: - How To Implement Ajax In Mvc(Model View  Controller) ?
Asp.Net Mvc Interview Question: – How To Implement Ajax In Mvc(Model View Controller) ?
Asp.Net Mvc: Ajax Dialog Form Using Jquery Ui | Nick Olsen'S Programming  Tips
Asp.Net Mvc: Ajax Dialog Form Using Jquery Ui | Nick Olsen’S Programming Tips
Github - Geeksarray/Jquery-Ajax-Autocomplete-In-Asp-Net-Mvc-Core: This  Tutorial Explains How To Use The Jquery Ajax Autocomplete Feature In Your  Asp.Net Mvc Core Application. For This, You Will Use Visual Studio 2019,  Net5, Ef Core, Web
Github – Geeksarray/Jquery-Ajax-Autocomplete-In-Asp-Net-Mvc-Core: This Tutorial Explains How To Use The Jquery Ajax Autocomplete Feature In Your Asp.Net Mvc Core Application. For This, You Will Use Visual Studio 2019, Net5, Ef Core, Web
Ajax Calls To .Net5 Mvc Controllers (Using Jquery) - Youtube
Ajax Calls To .Net5 Mvc Controllers (Using Jquery) – Youtube
Jquery Ajax Call To Mvc Controller With Parameters - Sensible Dev
Jquery Ajax Call To Mvc Controller With Parameters – Sensible Dev
Ajax Calls In Mvc Using Jquery - Youtube
Ajax Calls In Mvc Using Jquery – Youtube
Github - Codaffection/Jquery-Ajax-With-Asp.Net-Core-Mvc-Using-Modal-Popup
Github – Codaffection/Jquery-Ajax-With-Asp.Net-Core-Mvc-Using-Modal-Popup
Jquery Ajax Call To Mvc Controller With Parameters - Sensible Dev
Jquery Ajax Call To Mvc Controller With Parameters – Sensible Dev
Pass Multiple Parameters Using Jquery Ajax Asp.Net Mvc? - Youtube
Pass Multiple Parameters Using Jquery Ajax Asp.Net Mvc? – Youtube
Jquery Ajax Call To Mvc Controller With Parameters - Sensible Dev
Jquery Ajax Call To Mvc Controller With Parameters – Sensible Dev
Use Ajax To Deliver Dynamic Updates | Microsoft Learn
Use Ajax To Deliver Dynamic Updates | Microsoft Learn
How To Use Ajax And Jquery In Spring Web Mvc (.Jsp) Application • Crunchify
How To Use Ajax And Jquery In Spring Web Mvc (.Jsp) Application • Crunchify
Using Ajax In Asp.Net Mvc | Code2Night.Com
Using Ajax In Asp.Net Mvc | Code2Night.Com

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *