Chuyển tới nội dung
Home » Jquery Ajax Post Mvc | Subscription

Jquery Ajax Post Mvc | Subscription

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

Single Parameter

And the single one is just two small changes:

function calculate() { const data = { a: 1, b: 2 };

$.ajax({ url: ‘/Home/Add’, type: ‘POST’, data: JSON.stringify(data), contentType: ‘application/json’, success: function(result, status, xhr) { /*hooray!*/ }, error: function(xhr, status, error) { /*houston, we have a problem!*/ } }); }

As you can see, the difference is that here you need to explicitly serialize the data to JSON using the built-in JSON.stringify function and then also explicitly provide the content type application/json.

Pitfalls

There are a few possible pitfalls:

  1. You may get HTTP 400 Bad Request when you try to POST to your action method. This is likely because of Anti Cross Site Scripting Forgery (XSRF) protection, which is enabled by default in ASP.NET Core MVC. Please refer to my other post here, or, TL; DR, apply an [IgnoreAntiforgeryToken] to the action method
  2. When using the single parameter option, you may be getting a null value in the action method as the parameter value. This is likely the result of being unable to deserialize the contents that you are sending. Please ensure that you are allowing case-insensitive JSON serialization (the default) and that the parameters are well defined. See also here

Conclusion

AJAX has been around for quite a while and is a fun and safe option, but it has its tricks. Hope you find this post helpful!

In this article I will explain with an example, how to submit (POST) JavaScript FormData object to Controller using jQuery AJAX in ASP.Net MVC Razor.

Controller

There are two Action methods with the name Index, one for handling the GET operation while other for handling the POST operation.

The Action method for POST operation accepts an object of the FormCollection class as parameter.

Note: FormCollection class object is a Key-Value pair collection which provides access to data from the Request.Form collection.

The data posted using FormData object using jQuery AJAX is received through this parameter.

The fetched values are sent back to the View in String format using ContentResult.

public class HomeController : Controller

// GET: Home

public ActionResult Index()

return View();

[HttpPost]

public ContentResult Index(FormCollection formCollection)

int personId = int.Parse(formCollection[“PersonId”]);

string name = formCollection[“Name”];

string gender = formCollection[“Gender”];

string city = formCollection[“City”];

string message = “PersonId: ” + personId;

message += “\nName: ” + name;

message += “\nGender: ” + gender;

message += “\nCity: ” + city;

return Content(message);

View

The View consists of an HTML Table consisting of three TextBox fields created for capturing values for PersonId, Name and City using the Html.TextBox method. While for capturing the Gender value, a DropDownList with three options is created using the Html.DropDownList function.

There’s also an HTML Button which has been assigned a jQuery Click event handler.

Inside the jQuery Click event handler, first a JavaScript FormData object is created and the values of the TextBoxes and DropDownList are added to it.

Then using jQuery AJAX, the JavaScript FormData object is sent to the Controller’s Action method.

@{

Layout = null;

<br /> Index<br />

Person Details

PersonId:

@Html.TextBox(“PersonId”)

Name:

@Html.TextBox(“Name”)

Gender:

@Html.DropDownList(“Gender”, new List

{ new SelectListItem{Text=”Male”, Value=”M”},

new SelectListItem{Text=”Female”, Value=”F”}}, “Please select”)

City:

@Html.TextBox(“City”)

Screenshot

Downloads

GET

GET is used to request data from a specified resource. With all the GET request we pass the URL which is compulsory, however it can take the following overloads.


.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] ).done/.fail

Now, let’s try to use GET in MVC application.

GET call to Controller’s Method that will return string data

Let’s imagine we have the following method in the controller:


public string TellMeDate()
{
return DateTime.Today.ToString();
}

This method will return string data (date-time) when we call it, let’s make an async call using jQuery Ajax.

When the page gets loaded, jQuery Ajax will generate an Ajax GET request/call. The first parameter is the URL and the second is data (this is an optional, even we can avoid typing “null”) and the third is the success function when the response is received. The success function takes one parameter “data” that holds the string content and we attached this content to a DOM element.

If you want to generate an Ajax GET request when the user clicks a button then can use the following instead:

If you run the application, you will see the following output:

GET call with parameter to Controller’s Method that will return string data

Let’s imagine we have the following method in the controller:


public string WelcomeMsg(string input)
{
if (!String.IsNullOrEmpty(input))
return "Please welcome " + input + ".";
else
return "Please enter your name.";
}

This method will accept a parameter and will return string data (a welcome message or instruction message) when we call it. Now, let’s make an async call to this method using jQuery Ajax.

Enter you name @Html.TextBox("Name")


As you can see, when we click the button after typing a name in the TextBox, jQuery Ajax will generate an Ajax GET request/call. Notice that the second parameter to the “get” function now contains a key { input: name } (parameter). This example supplies one parameter, but can be extended to provide multiple parameters. The result of the preceding looks like the following:

GET call with parameter to Controller’s Method that will return JSON data

The Controller’s method we used above returns simple strings. Now, to deal with complex data we need JSON. The following method will return a JsonResult having the customer’s ContactName and Address from NorthwindEntities. I am using the Northwind database and EF Database First approach in this sample.


public JsonResult CustomerList(string Id)
{
NorthwindEntities db = new NorthwindEntities();
var result = from r in db.Customers
where r.Country == Id
select new { r.ContactName, r.Address };
return Json(result, JsonRequestBehavior.AllowGet);
}

The above method will accept Id as a parameter and return a “JsonResult”. This action method can be called using the following jQuery Ajax GET call:

Enter country name @Html.TextBox("Country")


As you can see, when we click the button after typing a country name in the TextBox, jQuery Ajax will generate an Ajax GET request/call. Notice that the “getJSON” function now contains an URL in the format “/Controller/ActionMethod/Key”, here the key (parameter) is the supplied country name. The result of the preceding looks like the following:

Using Firebug we can sniff the response. A screenshot is shown below:

In the above example we have used a TextBox where we typed the country name and clicked on a button to get the list of customers.

Alternatively, we can populate the list of countries in the dropdownlist box and then when the user selects the country name from the dropdownlist, we can display the list of customers.

Here is the controller that will populate the country list in the dropdownlist box:


public ActionResult About()
{
var result = from r in db.Customers
select r.Country;
ViewBag.Country = result;
return View();
}

Now, once we have a list of countries in the dropdownlist box, we can implement an Ajax GET request/call. Here it is with a complete view page.


@Html.DropDownListFor(model => model.Country, new SelectList(ViewBag.Country), "Select Country")

@section Scripts {

}

Everything remains the same as in the TextBox version above.

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

Multiple Parameters

Our action method will look like this:

[HttpPost] public IActionResult Add(int a, int b) { return Json(a + b); }

And that’s it, pretty simple, the [HttpPost] attribute, as you probably know, is an action attribute that says that this action can only be called as a result of an HTTP POST.

Let’s see now what the single parameter version would look like.

Subscription

Enter your name

@Html.TextBox(“Name”)

Enter your address

@Html.TextBox(“Address”)

@section Scripts{

}

Nothing new, everything is the same, just a few changes that allow us to work with a form.

I hope this helps.

Posting AJAX Requests to ASP.NET Core MVC

Introduction

In the past, I’ve had trouble doing something that is apparently simple: invoking a simple action method in a controller using AJAX. Although it is indeed simple, when using jQuery, it may require some attention, hence this post.

In this example I will show how to do something simple: how to invoke an action that just adds two integers and returns the result using jQuery AJAX. This can be extended to any other kind of data, mind you, it is not tied to simple data types.

Prerequisites

We will be using .NET Core (or .NET 5/6, doesn’t really matter for the purpose of this sample) and jQuery 3.x, although it should work the same with 2.x. There is no special setup required other than adding controllers and views to dependency injection (or full MVC, if you prefer).

Controller Side

The controller part is simple, but we have two options:

  1. We can have multiple parameters
  2. Or we can have a single parameter of a data type that holds all of the data that we wish to send

Generally, option #2 is more extensible, for we can add more parameters easily, without changing the action method’s signature, but I will show here how it works with both options.

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

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

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

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

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


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

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


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

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

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

Ví dụ:


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

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


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

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

Ví dụ:

Type : “POST”

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

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

Ví dụ:


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

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

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

Ví dụ:


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

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

Ví dụ:


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

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

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


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

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


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

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

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


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

Cách gọi trong jQuery ajax.

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


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

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

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


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

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


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


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

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

I’m a novice web programmer so please forgive me if some of my “jargon” is not correct. I’ve got a project using ASP.NET using the MVC3 framework.

I am working on an admin view where the admin will modify a list of equipment. One of the functions is an “update” button that I want to use jquery to dynamically edit the entry on the webpage after sending a post to the MVC controller.

I presume this approach is “safe” in a single admin setting where there is minimal concern of the webpage getting out of sync with the database.

I’ve created a view that is strongly typed and was hoping to pass the model data to the MVC control using an AJAX post.

In the following post, I found something that is similar to what I am looking at doing: JQuery Ajax and ASP.NET MVC3 causing null parameters

I will use the code sample from the above post.

Model:


public class AddressInfo { public string Address1 { get; set; } public string Address2 { get; set; } public string City { get; set; } public string State { get; set; } public string ZipCode { get; set; } public string Country { get; set; } }

Controller:


public class HomeController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Check(AddressInfo addressInfo) { return Json(new { success = true }); } }

script in View:

I have not had a chance to use the above yet. But I was wondering if this was the “best” method to pass the model data back to the MVC control using AJAX?

Should I be concerned about exposing the model information?

This blog will demonstrate, how to post the data to ASP.Net MVC controller(s) using JQuery Ajax. For that, I have created one controller “JQueryAjaxCallController” with the post action method “AjaxPostCall” and a class “Employee” as below.
Controller

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. namespace JQueryAjaxCallINMVC.Controllers {
  7. public class JQueryAjaxCallController: Controller {
  8. public ActionResult Index() {
  9. return View();
  10. [HttpPost]
  11. public JsonResult AjaxPostCall(Employee employeeData) {
  12. Employee employee = new Employee {
  13. Name = employeeData.Name,
  14. Designation = employeeData.Designation,
  15. Location = employeeData.Location
  16. };
  17. return Json(employee, JsonRequestBehavior.AllowGet);
  18. public class Employee {
  19. public string Name {
  20. get;
  21. set;
  22. public string Designation {
  23. get;
  24. set;
  25. public string Location {
  26. get;
  27. set;

View

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

Once you click the Add button, it will create strongly typed view with Employee model. Now we need to create Razor/Html controls to get the user input. Here, I used the HTML controls to get user input and we made a jQuery Ajax Post to call MVC controller in the below code.

  1. @model JQueryAjaxCallINMVC.Controllers.Employee
  2. @ {
  3. Layout = null;
  4. } < html > < head > < meta name = “viewport”
  5. content = “width=device-width” / > < title > JQUERY AJAX CALL < /title> < script type = “text/javascript”
  6. src = “https://code.jquery.com/jquery-1.12.4.js” > < /script> < script type = “text/javascript” > $(function() {
  7. $(“#btnPost”).click(function() {
  8. var employee = new Object();
  9. employee.Name = $(‘#txtName’).val();
  10. employee.Address = $(‘#txtDesignation’).val();
  11. employee.Location = $(‘#txtLocation’).val();
  12. if (employee != null) {
  13. $.ajax({
  14. type: “POST”,
  15. url: “/JQueryAjaxCall/AjaxPostCall”,
  16. data: JSON.stringify(employee),
  17. contentType: “application/json; charset=utf-8”,
  18. dataType: “json”,
  19. success: function(response) {
  20. if (response != null) {
  21. alert(“Name : ” + response.Name + “, Designation : ” + response.Designation + “, Location :” + response.Location);
  22. } else {
  23. alert(“Something went wrong”);
  24. },
  25. failure: function(response) {
  26. alert(response.responseText);
  27. },
  28. error: function(response) {
  29. alert(response.responseText);
  30. });
  31. });
  32. }); < /script> < /head> < body > < div style = “margin-left:20px” > JQuery Ajax POST call wtih ASP.NET MVC controller < /div> < br / > < div title = “PostPortion” > < input type = “text”
  33. id = “txtName”
  34. placeholder = “Name” / > < input type = “text”
  35. id = “txtDesignation”
  36. placeholder = “Designation” / > < input type = “text”
  37. id = “txtLocation”
  38. placeholder = “Location” / > < input type = “button”
  39. id = “btnPost”
  40. value = “Post Data” / > < /div> < /body> < /html>

Detailed Description

The JSON.stringify() method converts a JavaScript value to a JSON string. It’s optional when we are just passing parameter(s) with Values(s)
RouteConfig.Cs
You need to set your startup controller and view.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using System.Web.Routing;
  7. namespace JQueryAjaxCallINMVC {
  8. public class RouteConfig {
  9. public static void RegisterRoutes(RouteCollection routes) {
  10. routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
  11. routes.MapRoute(name: “Default”, url: “{controller}/{action}/{id}”, defaults: new {
  12. controller = “JQueryAjaxCall”, action = “Index”, id = UrlParameter.Optional
  13. });

Now run your application

Refer to the attached demo project and I hope it’s helpful.

Step 1 : Create an ASP.NET MVC Application.

Now let us start with a step by step approach from the creation of simple ASP.NET MVC application as in the following:

  1. “Start”, then “All Programs” and select “Microsoft Visual Studio 2015”.
  2. “File”, then “New” and click “Project…” then select “ASP.NET Web Application Template”, then provide the Project a name as you wish and click on OK .

Right click on model folder of created MVC application project and add class named Empmodel.cs

Empmodel.cs

public class EmpModel { public string Name { get; set; } public string City { get; set; } public string Address { get; set; } }

HomeController.cs

public class HomeController : Controller { private SqlConnection con; // GET: Home public ActionResult AddEmployee() { return View(); } //Post method to add details [HttpPost] public ActionResult AddEmployee(EmpModel obj) { AddDetails(obj); return View(); } //To Handle connection related activities private void connection() { string constr = ConfigurationManager.ConnectionStrings[“SqlConn”].ToString(); con = new SqlConnection(constr); } //To add Records into database private void AddDetails(EmpModel obj) { connection(); SqlCommand com = new SqlCommand(“AddEmp”, con); com.CommandType = CommandType.StoredProcedure; com.Parameters.AddWithValue(“@Name”, obj.Name); com.Parameters.AddWithValue(“@City”, obj.City); com.Parameters.AddWithValue(“@Address”, obj.Address); con.Open(); com.ExecuteNonQuery(); con.Close(); } }

Right click on View folder of created MVC application project and add empty view named AddEmployee.cshtml

Step 4: Create Jquery Post method

Now open the AddEmployee.cshtml view and create the following JQuery Post method to call controller .

To work with jQuery we need to reference of jQuery library.You can use following CDN jQuery library or you can use same file by downloading it as offline jQuery file.

Now after adding the library and form controls the AddEmployee.cshtml code will be look like as
Now everything is ready ,run the application and enter the details into the following form.

@{ ViewBag.Title = “www.compilemode.com”; }

Name
Address
City

After entering the details click on save button then the details will be get added into the database as

Note

  • Do a proper validation such as date input values when implementing.
  • Make the changes in the web.config file depending on your server details for the connection string.

Summary

In this article, I am going to cover some really interesting material that is very useful today in web application development. You will learn how to make jQuery Ajax GET and POST calls to controller methods.

When we use jQuery Ajax to access a server (controller’s method) without reloading the web page we have two choices for how to pass the information for the request to the server (controller’s method). These two options are to use either GET or POST.

Note: Before beginning with the code, ensure you are using the jQuery library before the GET or POST script.

Subscription

Enter your name

@Html.TextBox(“Name”)

Enter your address

@Html.TextBox(“Address”)


When you run the application above it will look like the following:

POST call to Controller’s Method to save form data

In case above we don’t have a form, so I have used two individual properties/parameters (name and address) with a jQuery Ajax POST call and also on the method side, but this approach will be painful since the number of properties increase. In this case we can use the model approach that will allow us to work with intelisense. So, let’s go and create the “Subscription” model class with two properties.


public class Subscription
{
public string Name { get; set; }
public string Address { get; set; }
}

Now that we have the model we can create our controller method:


[HttpPost]
public string SubmitSubscription(Subscription subs)
{
if (!String.IsNullOrEmpty(subs.Name) && !String.IsNullOrEmpty(subs.Address))
//TODO: Save the data in database
return "Thank you " + subs.Name + ". Record Saved.";
else
return "Please complete the form.";
}

Still the same, just using a model instead of individual properties.

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!

Single Parameter

public record AddRequest(int A, int B);

[HttpPost] public IActionResult Add([FromBody] AddRequest req) { return Json(req.A + req.B); }

Here we see a few more things:

  1. The parameter is decorated with a [FromBody] attribute. This one instructs ASP.NET Core MVC to provide the value for the parameter from the body of the request. Its usage could be skipped if we instead decorated the whole controller class with an [ApiController] attribute, but that is beyond the scope of this post

Client Side

On the client side, we also need to match the decision we made on the controller side, regarding how we defined the parameters.

POST

POST is used to submit data to be processed to a specified resource. With all the POST requests we pass the URL which is compulsory and the data, however it can take the following overloads.


.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )

Now, let's try to use POST in a MVC application.

POST call to Controller's Method to save TextBox data (not form)

There are various ways to POST form data to a method but in the example given below I'm not going to use any form. I will just use two textboxes and a submit button, when the user clicks the button I want to save the data using a jQuery Ajax POST call. So, here is the method accepting the two parameters for name and address:


[HttpPost]
public string SubmitSubscription(string Name, string Address)
{
if (!String.IsNullOrEmpty(Name) && !String.IsNullOrEmpty(Address))
//TODO: Save the data in database
return "Thank you " + Name + ". Record Saved.";
else
return "Please complete the form.";
}

We can implement method above to save the data in the database, it will also return the response back to the client. Here is the jQuery Ajax POST function:

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

Keywords searched by users: jquery ajax post mvc

Post Data To Controller Using Jquery Ajax In Asp.Net Mvc
Post Data To Controller Using Jquery Ajax In Asp.Net Mvc
Get And Post Calls To Controller'S Method In Mvc
Get And Post Calls To Controller'S Method In 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
Asp.Net Core Mvc Ajax Form Requests Using Jquery-Unobtrusive | Software  Engineering
Asp.Net Core Mvc Ajax Form Requests Using Jquery-Unobtrusive | Software Engineering
Sử Dụng Jquery Ajax Trong Asp.Net Mvc
Sử Dụng Jquery Ajax Trong Asp.Net Mvc
Jquery Send & Receive Json Object Using Ajax Post Asp Net Mvc With Example  - Youtube
Jquery Send & Receive Json Object Using Ajax Post Asp Net Mvc With Example - Youtube
Create Ajax Post To Mvc C# - Youtube
Create Ajax Post To Mvc C# - Youtube
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
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
Jquery Ajax Call To Mvc Controller With Parameters - Sensible Dev
Jquery Ajax Call To Mvc Controller With Parameters - Sensible Dev
Render Partialview Using Jquery Ajax In Asp.Net Mvc – Srinivasaraju'S Blog
Render Partialview Using Jquery Ajax In Asp.Net Mvc – Srinivasaraju'S Blog
Beginners Guide For Ajax Crud Using Jquery Datatables In Asp.Net Mvc 5
Beginners Guide For Ajax Crud Using Jquery Datatables In Asp.Net Mvc 5
Asp.Net Mvc: Ajax Dialog Form Using Jquery Ui | Nick Olsen'S Programming  Tips
Asp.Net Mvc: Ajax Dialog Form Using Jquery Ui | Nick Olsen'S Programming Tips
Asp.Net Mvc - Loading Partial Views Using Ajax/Jquery - Youtube
Asp.Net Mvc - Loading Partial Views Using Ajax/Jquery - Youtube
Asp.Net Mvc: Jquery Ajax Datatables With Dynamic Columns - Asma'S Blog
Asp.Net Mvc: Jquery Ajax Datatables With Dynamic Columns - Asma'S Blog
Getting Started With Jquery $.Ajax() – Back To Basics | Dotnetcurry
Getting Started With Jquery $.Ajax() – Back To Basics | Dotnetcurry
How To Use Jquery Ajax Method To Call An Action Method In Asp.Net Core
How To Use Jquery Ajax Method To Call An Action Method In Asp.Net Core
Jquery Ajax Call To Mvc Controller With Parameters - Sensible Dev
Jquery Ajax Call To Mvc Controller With Parameters - Sensible Dev
Jquery Ajax Post | How Does Jquery Ajax Post Work With Examples?
Jquery Ajax Post | How Does Jquery Ajax Post Work With Examples?
Ajax And Jquery In Asp.Net Mvc | Chsakell'S Blog
Ajax And Jquery In Asp.Net Mvc | Chsakell'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 *