Chuyển tới nội dung
Home » Jquery Ajax Call In Mvc | Sử Dụng Jquery Ajax Trong Asp.Net Mvc

Jquery Ajax Call In Mvc | Sử Dụng Jquery Ajax Trong Asp.Net Mvc

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

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

ASP AJAX

AJAX is about updating parts of a web page, without reloading the whole 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!

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.

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!

In this article I will explain with an example, how to call Controller with GET call using jQuery AJAX in ASP.Net MVC.

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 GET call made from the jQuery AJAX function from the View.

Note: By default, ASP.Net MVC does not allow JSON GET call and hence it needs to be explicitly allowed using the JsonRequestBehavior.AllowGet behavior.

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

[HttpGet]

public JsonResult AjaxMethod(string name)

PersonModel person = new PersonModel

Name = name,

DateTime = DateTime.Now.ToString()

};

return Json(person, JsonRequestBehavior.AllowGet);

Typical GET call using jQuery AJAX

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

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 TYPE is set to GET and 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_GET_MVC.Models.PersonModel

@{

Layout = null;

<br /> Index<br />

Screenshot

Downloads

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

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

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!

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

POST type Ajax Call

POST type ajax call is used when we want to submit form data or user inputs to the backend side. inputs data does not gets appended to the AJAX call URL. but it sends Inputs data as request body.here we are using ASP.NET MVC as backend.So for better understanding let’s see below AJAX call example:

Ajax POST Example


Your Email is :
Password:


$("#registerForm").on("submit", function (e) { e.preventDefault(); //to prevent page reload on form submit var formData = $(this).serialize(); $.ajax({ url: "/home/Register", //url of {controller/action} type: "POST", //type of request (http verb) data: formData, //formData to submit success: function (response) { if (response == false) { // error message $("#divResponse").hide(); $("#status").html("oops something went wrong!") } else { //showing results $("#divResponse").show(); $("#status").html("user successfully registered!") $("#spnEmail").html(response.Email); $("#spnPass").html(response.Password) } }, error: function (xhr) { //on error response } }); });

In above code you can see two code example,One is HTML code blockSecond is Javascript code blockYou can place both HTML and Javascript code in a Single file Index.cshtml or any .cshtml page you have.Now let’s say I want to submit all user input of form which id is

registerForm

. so for that I will use

$(this).serialize()

which will collect all the user inputs of form.And In above Javascript Code you see that I am collecting form data of FORM

registerForm

in a variable named

formData

which is on line no:3 of Javascript code and passing that formData to the data: property of ajax call.The

data

property is used to pass the input data to the controller action. The controller action will then process the data and return a response.


namespace ajaxExample.Models { public class Register { public string Email { get; set; } public string Password { get; set; } } }

In above code block we can see that, we have created a model named “Register” for parsing formData inputs as a model class.parsing of formData to model class done automatically by .NET MVC. but name of model properties should be same as formData input name.


[HttpPost] public ActionResult Register(Register register) { if (register != null && register.Email != null && register.Password != null) { //your code to register user return Json(register, JsonRequestBehavior.AllowGet); } else { return Json(false, JsonRequestBehavior.AllowGet); }

In above

ActionMethod

of HomeController,

register

parameter type of

Register

class contains the data sent by AJAX call.And we are validating here that if the data sent by AJAX call is null or not, after validating the request we are pushing the same request model as JSON response.Again,

JsonRequestBehavior.AllowGet

is mandatory. so we can read data on completion of AJAX call.

Ajax GET Example

my name is :



public JsonResult GetName() { return Json("ankit", JsonRequestBehavior.AllowGet); }

In above example Index.cshtml have Ajax call which will trigger on click of button “Get Name”. by clicking on button it will trigger AJAX call and call

HomeController/GetName

method and will return static text “ankit”.For the demo purpose I have returned a static text

"ankit"

but you can write business logic and return anything as JSON response.

JsonRequestBehavior.AllowGet

is mandatory for pushing data as json response otherwise you may face issue while accessing the response result of the function.

Output

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!

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!

Step 1: Add jQuery library

In your ASP.NET MVC project, add the jQuery library to the project. You can do this by adding a reference to the jQuery library in the project’s References folder.

or

You can also download jQuery Scripts and place it in /Scripts folder of your ASP.NET MVC project. click on below link to download jQuery.

Mainly there are two types of jQuery ajax call :

  1. GET
  2. POST
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

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.

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.

ASP.NET CORE : Call Controller Action Method using JQuery AJAX
ASP.NET CORE : Call Controller Action Method using JQuery AJAX

Ajax Call Getting started

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

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)
Ajax Calls in MVC using jQuery
Ajax Calls in MVC using jQuery

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

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 Core MVC CRUD Operations using jQuery ajax call (Entity Framework Core + Client validation)
ASP.NET Core MVC CRUD Operations using jQuery ajax call (Entity Framework Core + Client validation)

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.

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

%>

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.

In this article, we will see how to write a jQuery AJAX call in ASP.NET MVC.

jQuery Ajax In Asp.Net MVC - CRUD Operations Using JSON
jQuery Ajax In Asp.Net MVC – CRUD Operations Using JSON

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.

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.

.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

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.

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

Keywords searched by users: jquery ajax call in mvc

Calling A C# Function With Jquery Ajax In Asp.Net Mvc
Calling A C# Function With Jquery Ajax In Asp.Net Mvc
Ajax Calls To .Net5 Mvc Controllers (Using Jquery) - Youtube
Ajax Calls To .Net5 Mvc Controllers (Using Jquery) – Youtube
Post Form Data To Controller In Asp.Net Mvc Using Ajax - Dotnetxp
Post Form Data To Controller In Asp.Net Mvc Using Ajax – Dotnetxp
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
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
Javascript Ajax Calls In Mvc - Part 9 | Tamil | Course | Dharanz - Youtube
Javascript Ajax Calls In Mvc – Part 9 | Tamil | Course | Dharanz – Youtube
Sử Dụng Jquery Ajax Trong Asp.Net Mvc
Sử Dụng Jquery Ajax Trong Asp.Net Mvc
Problem Passing A Record Size From Ajax To Controller In Asp Net Core 5 Mvc  - Microsoft Q&A
Problem Passing A Record Size From Ajax To Controller In Asp Net Core 5 Mvc – Microsoft Q&A
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
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
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
Render Partialview Using Jquery Ajax In Asp.Net Mvc – Srinivasaraju'S Blog
Render Partialview Using Jquery Ajax In Asp.Net Mvc – Srinivasaraju’S Blog

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 *