Skip to content
Home » Mvc With Jquery Ajax Example | What Is Ajax?

Mvc With Jquery Ajax Example | What Is Ajax?

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

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!

Before diving into the core topic let’s have an overview about JQuery and Ajax. What is it? What is JQuery? Well, JQuery is a framework (tools) for writing JavaScript, Written as “write less, do more”, jQuery is to make easier to use JavaScript. What is JavaScript? JavaScript is an object-oriented computer programming (Scripting) language commonly used to create interactive effects within web browsers. Let’s have a sample example: We have a submit button in our JQuery AJAX MVC application. Let’s try to show a message when it is clicked. Here is our button with defined id=”btnSubmit”:

Now we need to write some script to do that, here is some JavaScript code:

  1. var myBtn = document.getElementById(‘btnSubmit’);
  2. myBtn.addEventListener(‘click’, function(e) {
  3. e.preventDefault();
  4. alert(‘Hello’);
  5. });

By this code the result will show “Hello”: Now if we can get the same result by using jQuery instead of it. Let’s have a look:

  1. $(‘#btnSubmit’).click(function(event) {
  2. event.preventDefault();
  3. alert(“Hello”);
  4. });

Note: Here use of ‘e’ is just a short for event which raised the event. We can pass any variable name. Notice that the ‘e’ is changed to name ‘event’ in JQuery part. This piece of code is also producing the same result “Hello”. This is why jQuery is known as “write less, do more”. Finally the script:

Let’s focus on Ajax: AJAX stands for “Asynchronous JavaScript and XML”. AJAX is about exchanging data with a server, without reloading the whole page. It is a technique for creating fast and dynamic web pages. In .NET, we can call server side code using two ways:

  1. ASP .NET AJAX
  2. jQuery AJAX

In this article we will focus on JQuery Ajax. $.ajax () Method: JQuery’s core method for creating Ajax requests. Here are some jQuery AJAX methods:

  • $.ajax() Performs an async AJAX request.
  • $.get() Loads data from a server using an AJAX HTTP GET request.
  • $.post() Loads data from a server using an AJAX HTTP POST request.

To know more click. $.ajax () Method Configuration option: Options that we use:

  • async:
  • type:
  • url:
  • data:
  • datatype:
  • success:
  • error:

Let’s have details overview: async Set to false if the request should be sent synchronously. Defaults to true. Note that if you set this option to false, your request will block execution of other code until the response is received. Example:

type This is type of HTTP Request and accepts a valid HTTP verb. The type of the request, “POST” or “GET” defaults to “GET”. Other request types, such as “PUT” and “DELETE” can be used, but they may not be supported by all the web browsers. Example:

url The URL for the request. Example:

data The data to be sent to the server. This can either be an object or a query string. Example:

  1. data: JSON.stringify(model_data),

dataType The type of data you expect back from the server. By default, jQuery will look at the MIME type of the response if no dataType is specified. Accepted values are text, xml, json, script, html jsonp. Example:

contentType This is the content type of the request you are making. The default is ‘application/x-www-form-urlencoded’. Example:

  1. contentType: ‘application/json; charset=utf-8’,

success A callback function to run if the request succeeds. The function receives the response data (converted to a JavaScript object if the DataType was JSON), as well as the text status of the request and the raw request object.

  1. Success: function (result) {
  2. $(‘#result’).html(result);

error A callback function to run if the request results in an error. The function receives the raw request object and the text status of the request.

  1. error: function (result) {
  2. alert(‘Error occured!!’);
  3. },

Let’s Post Values using JQuey,Ajax: We often use the jQuery Ajax method in ASP.NET Razor Web Pages. Here is a sample code:

Controller Action:

  1. [HttpPost]
  2. public ActionResult JqAJAX(Student st) {
  3. try {
  4. return Json(new {
  5. msg = “Successfully added ” + st.Name
  6. });
  7. } catch (Exception ex) {
  8. throw ex;

Posting JSON JSON is a data interchange format where values are converted to a string. The recommended way to create JSON is include the JSON.stringify method. In this case we have defined:

And the data type set to:

And the content type set to application/json

  1. contentType: ‘application/json; charset=utf-8’

Syntax: JSON.stringify(value[, replacer[, space]]) Post Script:

  1. var Student = {
  2. ID: ‘10001’,
  3. Name: ‘Shashangka’,
  4. Age: 31
  5. };
  6. $.ajax({
  7. type: “POST”,
  8. url: “/Home/JqAJAX”,
  9. data: JSON.stringify(Student),
  10. contentType: ‘application/json; charset=utf-8’,
  11. success: function(data) {
  12. alert(data.msg);
  13. },
  14. error: function() {
  15. alert(“Error occured!!”)
  16. });

Controller Action:

  1. [HttpPost]
  2. public ActionResult JqAJAX(Student st) {
  3. try {
  4. return Json(new {
  5. msg = “Successfully added ” + st.Name
  6. });
  7. } catch (Exception ex) {
  8. throw ex;

JSON Response Result: Sent data format: {“ID”:”10001″,”Name”:”Shashangka”,”Age”:31} Received Data format: {“msg”:”Successfully added Shashangka”} Let’s Post JavaScript Objects: To send JavaScript Objects we need to omit the JSON.stringify(Student) method and we need to pass the plain object to the data option. In this case we have defined:

And the datatype set to:

And the content type set to default.

  1. contentType: ‘application/x-www-form-urlencoded’

Post Script:

  1. var Student = {
  2. ID: ‘10001’,
  3. Name: ‘Shashangka’,
  4. Age: 31
  5. };
  6. $.ajax({
  7. type: “POST”,
  8. url: “/Home/JqAJAX”,
  9. data: Student,
  10. contentType: ‘application/x-www-form-urlencoded’,
  11. datatype: “html”,
  12. success: function(data) {
  13. alert(data.msg);
  14. },
  15. error: function() {
  16. alert(“Error occured!!”)
  17. });

Controller Action:

  1. [HttpPost]
  2. public ActionResult JqAJAX(Student st) {
  3. try {
  4. return Json(new {
  5. msg = “Successfully added ” + st.Name
  6. });
  7. } catch (Exception ex) {
  8. throw ex;

JavaScript Objects Response Result: Sent data format: ID=10001&Name=Shashangka&Age=31 Received Data format: {“msg”:”Successfully added Shashangka”} Let’s Post JavaScript Arrays: To send Array we need to omit the JSON.stringify(Student) method and we need to pass the plain object to the data option. In this case we have defined:

And the datatype set to:

And the content type set to default

  1. contentType: ‘application/x-www-form-urlencoded’

Post Script:

  1. var ID = [“Shashangka”, “Shekhar”, “Mandal”];
  2. $.ajax({
  3. type: “POST”,
  4. url: “/Home/JqAJAX”,
  5. data: {
  6. values: ID
  7. },
  8. datatype: “html”,
  9. contentType: ‘application/x-www-form-urlencoded’,
  10. success: function(data) {
  11. alert(data.msg);
  12. },
  13. error: function() {
  14. alert(“Error occured!!”)
  15. });

Controller Action:

  1. [HttpPost]
  2. public ActionResult JqAJAX(string[] values) {
  3. try {
  4. return Json(new {
  5. msg = String.Format(“Fist Name: {0}”, values[0])
  6. });
  7. } catch (Exception ex) {
  8. throw ex;

Array Response Result: Sent data format: values[]=Shashangka&values[]=Shekhar&values[]=Mandal Received Data format: {“msg”:”Fist Name: Shashangka”} Hope this will help to understand different datatypes and Ajax posting. Thanks!

On my MVC View I have button:

When I click this button I need call one Action, do some stuff there and then Submit my form.

I have this jQuery:


$('#btnSave').click(function () { $.ajax({ url: "/Home/SaveDetailedInfo", type: "POST", data: JSON.stringify({ 'Options': someData}), dataType: "json", traditional: true, contentType: "application/json; charset=utf-8", success: function (data) { if (data.status == "Success") { alert("Done"); } else { alert("Error occurs on the Database level!"); } }, error: function () { alert("An error has occured!!!"); } }); });

Then I want to submit my form. In Controller I have 2 Actions:


public ActionResult SaveDetailedInfo(Option[] Options) { return Json(new { status = "Success", message = "Success" }); } [HttpPost] public ActionResult Save() { return RedirectToAction("Index", "Home"); }

The problem is when I have

type="submit"

in my button, I can’t reach

SaveDetailedInfo

Action, cause ajax gives me

error

, but when I remove

type="submit"

, ajax works fine, but

Save

Action never executes.

Please, any ideas how to execute both Actions? I thought maybe after

Ajax > Success

try to add

type=submit

through jquery and use

.click()

, but it sounds strange to me.

Khóa học này là một khóa học ngắn giúp các bạn tạo một màn hình thêm sửa xóa tìm kiếm phân trang sử dụng ASP.NET MVC và JQuery AJAX để thao tác là chính.

Nhằm giúp các bạn hiểu cách làm việc từ backend đến frontend, TEDU làm một khóa học nhỏ giúp các bạn tập làm việc với JQuery AJAX sử dụng ASP.NET MVC làm controller backend để truy cập dữ liệu. Trong khóa học có sử dụng Entity Framework CodeFirst để migration dữ liệu.

Kết thúc khóa học này học viên có thể thêm sửa xóa tìm kiếm và phân trang dữ liệu trong bảng với Bootstrap modal popup và Jquery AJAX. Đồng thời hiểu được cách phân trang dữ liệu lớn trong AJAX MVC.

Họ và tên: Toàn Bạch

Nghề nghiêp: Senior Fullstack .NET Developer

Kỹ năng: Có hơn 8 năm làm dự án về ASP.NET MVC, WebForm, Web Service, Web API, ASP.NET Core, Angular SQL Server, JQuery, SOLID, Design Pattern, DevOps.

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.

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!

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

Summary

In this article, we examined Jquery AJAX enabled ASP.NET MVC application using

$.get()

and

$.getJSON()

. We built a Weather forecast application by consuming a web service which is freely available at WebserviceX.NET.

This member has not yet provided a Biography. Assume it’s interesting and varied, and probably something to do with programming.

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

Using the Code

To reference the Jquery AJAX script libraries, add the following markup at the end of the head element in

Site.Master

:

One thing to note is that Jquery can be loaded from Google, jquery site or a local folder. However, I will personally use Google hosted as it will improve the site performance, see Test Drive of the Google Hosted Ajax Libraries.

I will use JQuery

get()

method and here is our View:

<%@ Page Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master”
Inherits=”System.Web.Mvc.ViewPage” %>

Home Page

In the above code:

  1. Our view is loading a remote page using an HTTP

    GET

    request.

  2. var URL = "/Weather/GetWeather/"

    is a URL with parameters

    "{controller}/{action}/{id}"

  3. $.get(URL, function(data)

    method takes 2 parameters, URL and the callback function to pass the data returned from the call.

ASP.NET MVC checks incoming URL requests against routes in the order they were registered. Therefore, the above URL is required to register in the “Global.asax” file. Here is our Global.asax.

routes.MapRoute(“Jquery”, “Weather/GetWeather/{Id}”,
new { controller = “Weather”, action = “GetWeather” });

Now, I will create a

WeatherController

class that will have a

GetWeather

action as it is defined in our Global.asax. Here is our WeatherController.cs.

public class WeatherController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult GetWeather(string Id)
{
StringBuilder sb = new StringBuilder();
WeatherForecast wf = new WeatherForecast();
WeatherForecasts wfs = wf.GetWeatherByPlaceName(Id);
WeatherData[] wd = wfs.Details;
sb.AppendFormat(”

Weather Forecast for {0}

“, wfs.PlaceName);
foreach (WeatherData d in wd)
{
if(!string.IsNullOrEmpty(d.WeatherImage))
{
sb.AppendFormat(“”, d.WeatherImage);
sb.AppendFormat(” {0}”, d.Day);
sb.AppendFormat(“, High {0}F”, d.MaxTemperatureF);
sb.AppendFormat(“, Low {0}F”, d.MinTemperatureF);
}
}
Response.Write(sb.ToString());
return null;
}
}

To reference the web service in our controller class, see my previous article. Now you can run the application and it will render the page as shown below:

Now, I will use the

getJSON()

method to make the above call and here is my modified view with

getJSON()

method as shown below:

<%@ Page Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master”
Inherits=”System.Web.Mvc.ViewPage” %>

Home Page

In the above code:

  1. Our view is loading JSON data using an HTTP

    GET

    request.

  2. var URL = "/Weather/GetJsonWeather/"

    is a URL with parameters

    "{controller}/{action}/"

    that returns a

    JsonResult

    .

  3. $.getJSON(URL, { Location: $("#Location").val() }, function(data)

    JQuery JSON method takes 3 parameters, URL, data (which is location in our call) and the callback function to pass the data returned from the call. Then we use

    $.each()

    to iterate the json data.

Now, I will build

GetJsonWeather

method in our WeatherController.cs class as shown below:

public class WeatherController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult GetJsonWeather(string location)
{
WeatherForecast wf = new WeatherForecast();
WeatherForecasts wfs = wf.GetWeatherByPlaceName(location);
return Json(wfs.Details);
}
}

One thing to note is that our both methods

$.get()

and

$.getJSON()

will produce the same output as shown above.

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

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!

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

Introduction

The JQuery has the following methods that can be used to perform Ajax requests:


  1. ajax()

    – Load a remote page using an HTTP request. This is jQuery’s low-level AJAX implementation.

  2. load()

    – Load HTML from a remote file and inject it into the DOM.

  3. get()

    – Load a remote page using an HTTP

    GET

    request.

  4. getJSON()

    – Load JSON data using an HTTP

    GET

    request.

  5. getScript()

    – Loads, and executes, a local JavaScript file using an HTTP

    GET

    request.

  6. post()

    – Loads HTML by performing an HTTP

    post

    request.
ASP.NET MVC Tutorials - Using jQuery Ajax in ASP.NET MVC.
ASP.NET MVC Tutorials – Using jQuery Ajax in ASP.NET MVC.

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.

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!

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

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.

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

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.

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.

jQuery Send & Receive JSON Object using ajax post asp net mvc with Example
jQuery Send & Receive JSON Object using ajax post asp net mvc with Example

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 –

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.

.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

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!

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.
FULL MATCH: MÃ Minh Cẩm - Frederic CAUDRON | Bán Kết PBA - Silkroad & Ansan PBA Championship 23-24
FULL MATCH: MÃ Minh Cẩm – Frederic CAUDRON | Bán Kết PBA – Silkroad & Ansan PBA Championship 23-24

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.

Keywords searched by users: mvc with jquery ajax example

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
Asp.Net Mvc - Jquery Ajax Datatables With Dynamic Columns
Asp.Net Mvc – Jquery Ajax Datatables With Dynamic Columns
Crud Operations In Mvc | Using Jquery Ajax | Part-1 Retrieve Database Data  & Show In A View - Youtube
Crud Operations In Mvc | Using Jquery Ajax | Part-1 Retrieve Database Data & Show In A View – Youtube
Ajax And Jquery In Asp.Net Mvc | Chsakell'S Blog
Ajax And Jquery In Asp.Net Mvc | Chsakell’S Blog
Hectorcorrea.Com
Hectorcorrea.Com
Grid View For Aps.Net Mvc - How To Use The Jquery.Ajax Function With  Devexpress Mvc Extensions | Devexpress Support
Grid View For Aps.Net Mvc – How To Use The Jquery.Ajax Function With Devexpress Mvc Extensions | Devexpress Support
Jquery Ajax Get And Post Calls To Controller'S Method In Mvc
Jquery Ajax Get And Post Calls To Controller’S Method In Mvc
Jquery Ajax In Asp.Net Mvc - Crud Operations Using Json - Youtube
Jquery Ajax In Asp.Net Mvc – Crud Operations Using Json – Youtube
Spring Mvc Jquery Ajax Example: Hướng Dẫn Thực Hành - Hanoilaw Firm
Spring Mvc Jquery Ajax Example: Hướng Dẫn Thực Hành – Hanoilaw Firm
Jquery Ajax Json Example In Asp.Net To Insert Data Into Sql Server Database  Without Postback ~ Asp.Net,C#.Net,Vb.Net,Mvc,Jquery,Javascipt,Ajax,Wcf,Sql  Server Example
Jquery Ajax Json Example In Asp.Net To Insert Data Into Sql Server Database Without Postback ~ Asp.Net,C#.Net,Vb.Net,Mvc,Jquery,Javascipt,Ajax,Wcf,Sql Server Example
Post Form Data To Controller In Asp.Net Mvc Using Ajax - Dotnetxp
Post Form Data To Controller In Asp.Net Mvc Using Ajax – Dotnetxp
Ajax Calls To .Net5 Mvc Controllers (Using Jquery) - Youtube
Ajax Calls To .Net5 Mvc Controllers (Using Jquery) – Youtube
Getting Started With Jquery $.Ajax() – Back To Basics | Dotnetcurry
Getting Started With Jquery $.Ajax() – Back To Basics | Dotnetcurry
Post Data To Controller Using Jquery Ajax In Asp.Net Mvc
Post Data To Controller Using Jquery Ajax In Asp.Net Mvc
Posting Javascript Types To Mvc 6 In .Net Core, Using Ajax | I Came, I  Learned, I Blogged
Posting Javascript Types To Mvc 6 In .Net Core, Using Ajax | I Came, I Learned, I Blogged
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

See more here: kientrucannam.vn

Leave a Reply

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