Skip to content
Home » Ajax Call In Mvc 5 Example | Example Explained – The Html Page

Ajax Call In Mvc 5 Example | Example Explained – The Html Page

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

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!

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.

(#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#

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.

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.:

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.

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

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!

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

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.:

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.

(#40) Post data using ajax in mvc | Asp.Net MVC 5 tutorial-step by step in Hindi
(#40) Post data using ajax in mvc | Asp.Net MVC 5 tutorial-step by step in Hindi

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(“”)

%>

AJAX helps you to load data in the background and display it on the webpage, without reloading the complete webpage. It provides a smoother user experience while you are working with paging, sorting or filtering features in FlexGrid. This topic describes how to bind a FlexGrid at client side using an AJAX call.

This topic comprises the following steps:

The following image shows how the FlexGrid appears after completing the steps above:

Back to Top


Sale.cs. For more information on how to add a new model, see Adding Controls.


Sale.csmodel. We are using Sale class to represent sales order data in the database. Each instance of Sale object will correspond to a record in the FlexGrid control.

Sale.cs

Copy Code

using System; using System.Collections.Generic; using System.Linq; namespace AjaxDataBinding.Models { public class Sale { public int ID { get; set; } public DateTime Start { get; set; } public DateTime End { get; set; } public string Country { get; set; } public string Product { get; set; } public string Color { get; set; } public double Amount { get; set; } public double Amount2 { get; set; } public double Discount { get; set; } public bool Active { get; set; } public MonthData[] Trends { get; set; } public int Rank { get; set; } private static List

COUNTRIES = new List

{ “US”, “UK”, “Canada”, “Japan”, “China”, “France”, “German”, “Italy”, “Korea”, “Australia” }; private static List

PRODUCTS = new List

{ “Widget”, “Gadget”, “Doohickey” }; ///

/// Get the data. ///

/// /// public static IEnumerable

GetData(int total) { var colors = new[] { “Black”, “White”, “Red”, “Green”, “Blue” }; var rand = new Random(0); var dt = DateTime.Now; var list = Enumerable.Range(0, total).Select(i => { var country = COUNTRIES[rand.Next(0, COUNTRIES.Count – 1)]; var product = PRODUCTS[rand.Next(0, PRODUCTS.Count – 1)]; var color = colors[rand.Next(0, colors.Length – 1)]; var startDate = new DateTime(dt.Year, i % 12 + 1, 25); var endDate = new DateTime(dt.Year, i % 12 + 1, 25, i % 24, i % 60, i % 60); return new Sale { ID = i + 1, Start = startDate, End = endDate, Country = country, Product = product, Color = color, Amount = Math.Round(rand.NextDouble() * 10000 – 5000, 2), Amount2 = Math.Round(rand.NextDouble() * 10000 – 5000, 2), Discount = Math.Round(rand.NextDouble() / 4, 2), Active = (i % 4 == 0), Trends = Enumerable.Range(0, 12).Select(x => new MonthData { Month = x + 1, Data = rand.Next(0, 100) }).ToArray(), Rank = rand.Next(1, 6) }; }); return list; } public static List

GetCountries() { var countries = new List

(); countries.AddRange(COUNTRIES); return countries; } public static List

GetProducts() { List

products = new List

(); products.AddRange(PRODUCTS); return products; } } public class MonthData { public int Month { get; set; } public double Data { get; set; } } }










HomeController.csfrom the Controllers folder.

C#

Copy Code

[HttpPost] public JsonResult GetData() { List

saleList = Sale.GetData(10).ToList

(); return Json(saleList); }


Index.htmlfrom View/Home folder.

HTML

Copy Code

We’ll bind data to the control on the client side using JavaScript to make an AJAX call to the Action created in the HomeController.cs file. When we bind the grid at client-side in the Load function below, instead of assigning the result data of AJAX call to FlexGrid itemSource property, we should update the sourceCollection of FlexGrid’s collectionView at client-side to retain the server-side features of collectionView. We have also added a code check for any errors in date values of JSON data.


Index.htmlfile inside the Home folder and copy the following JavaScript code.

Index.html

Copy Code

Index.html

Copy Code

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.

ASP.NET MVC -  #28: Cách gọi AJAX trong ASP.NET MVC | AJAX call in ASP.NET MVC | TEDU
ASP.NET MVC – #28: Cách gọi AJAX trong ASP.NET MVC | AJAX call in ASP.NET MVC | TEDU

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)

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

ASP.NET MVC 5 : 5.1 AJAX - AJAX calls
ASP.NET MVC 5 : 5.1 AJAX – AJAX calls

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.

ASP AJAX

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

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.

MVC 5 Master Details Using Jquery Ajax | Entity Framework
MVC 5 Master Details Using Jquery Ajax | Entity Framework

I have tried to use AJAX call in an MVC5 project as many similar examples on the web, but every time there is an error i.e. antiforgerytoken, 500, etc. I am looking at a proper AJAX call method with Controller Action method that has all the necessary properties and sending model data from View to Controller Action. Here are the methods I used:

View:


@using (Html.BeginForm("Insert", "Account", FormMethod.Post, new { id = "frmRegister" })) { @Html.AntiForgeryToken() //code omitted for brevity }

Controller: Code cannot hit to this Action method due to antiforgerytoken or similar problem.


[HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public JsonResult Insert(RegisterViewModel model) { try { //... //code omitted for brevity } }

I just need a proper AJAX and Action methods that can be used for CRUD operations in MVC5. Any help would be appreciated.

UPDATE: Here is some points about which I need to be clarified:

1) We did not use “__RequestVerificationToken” and I am not sure if we send it to the Controller properly (it seems to be as cookie in the Request Headers of Firebug, but I am not sure if it is OK or not). Any idea?

2) Should I use var formdata = new FormData($(‘#frmRegister’).get(0)); when I upload files?

3) Why do I have to avoid using processData and contentType in this scenario?

4) Is the Controller method and error part of the AJAX method are OK? Or is there any missing or extra part there?

Ajax Call Getting started

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

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 CORE : Call Controller Action Method using JQuery AJAX
ASP.NET CORE : Call Controller Action Method using 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 call in mvc 5 example

Ajax Calls In Mvc Using Jquery - Youtube
Ajax Calls In Mvc Using Jquery – Youtube
40) Post Data Using Ajax In Mvc | Asp.Net Mvc 5 Tutorial-Step By Step In  Hindi - Youtube
40) Post Data Using Ajax In Mvc | Asp.Net Mvc 5 Tutorial-Step By Step In Hindi – Youtube
Call Controller Using Jquery Ajax In Asp.Net Core Mvc - Youtube
Call Controller Using Jquery Ajax In Asp.Net Core Mvc – Youtube
An Introduction To Ajax In Asp.Net | Simplilearn
An Introduction To Ajax In Asp.Net | Simplilearn
How To Use Jquery Ajax Method To Call An Action Method In Asp.Net Core
How To Use Jquery Ajax Method To Call An Action Method In Asp.Net Core
Jquery Ajax Methods
Jquery Ajax Methods

See more here: kientrucannam.vn

Leave a Reply

Your email address will not be published. Required fields are marked *