Skip to content
Home » Ajax Post Example Mvc | The Asp File

Ajax Post Example Mvc | The Asp File

Ajax calls to .Net5 MVC Controllers (using JQuery)

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.

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 to .Net5 MVC Controllers (using JQuery)
Ajax calls to .Net5 MVC Controllers (using JQuery)

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

%>

Hi @Ted ,

As Bruce-SqlWork said, to pass data from view to the controller, we need to add the data to the request URL (use the query string, then the request URL like this:

/Home/Index?Ticker=AAA

) or submit a form (use the tag).

General, in the index page, it will use the display a list of userInput, then, if you also want to create new userInput, you could use a tag to submit a form to insert new records.

The Index.cshtml like this: Note: At the top of the page, we are using an IEnumerable or List type to receive the returned model from the action. Then in the form tag, we are using an input element with the name

Ticker

, after submitting the form, in the action method, it will get the value via the name attribute.


@model IEnumerable

@{
ViewData["Title"] = "Index";
}

Index

@foreach (var item in Model) {

}

@Html.DisplayNameFor(model => model.Ticker)
@Html.DisplayFor(modelItem => item.Ticker)
Edit

|

Details

|

Delete


Then, the controller like this:


public class RequestPrototypeController : Controller
{
private readonly ApplicationDbContext _dbcontext;
public RequestPrototypeController(ApplicationDbContext applicationDbContext)
{
_dbcontext = applicationDbContext;
}
public IActionResult Index(string Ticker)
{
if (!string.IsNullOrEmpty(Ticker))
{
//if tricker is not null, insert the value into database.
_dbcontext.UserInput.Add(new userInput() { Ticker = Ticker });
_dbcontext.SaveChanges();
}
//define a list to store the latest data.
var items = new List

();
//get the latest data from database.
items = _dbcontext.UserInput.ToList();
//return the data to the view page.
return View(items);
}

Then, the output like this:

Besides, you can also create a Create page to create the new item, then the Create page like this:

Create.cshtml: Note: in this page, the page model is userInput, and we can use asp.net core tag helper to bind property


@model WebApplication2.Models.userInput
@{
ViewData["Title"] = "Create";
}

Create

userInput

The Create action methods:


public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(userInput userInput)
{
//check whether the model is valid or not
if (!ModelState.IsValid)
{
//if not valid, return to the create page with the userinput model
return View(userInput);
}
//if model is valid, insert the data into database.
_dbcontext.UserInput.Add(new userInput() { Ticker = userInput.Ticker });
_dbcontext.SaveChanges();
//redirect to the index action to display the latest data.
return RedirectToAction(nameof(Index));
}

Then, the output like this:

More detail information, refer the following tutorials:

Part 6, controller methods and views in ASP.NET Core

Views in ASP.NET Core MVC

Tutorial: Implement CRUD Functionality – ASP.NET MVC with EF Core

If the answer is the right solution, please click “Accept Answer” and kindly upvote it. If you have extra questions about this answer, please click “Comment”.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Best regards,
Dillion

jQuery serialize() Method

Example

Output the result of serialized form values:

$(“button”).click(function(){$(“div”).text($(“form”).serialize());});

Try it Yourself »

$(“div”).text($(“form”).serialize());

});

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.

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

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.

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!

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

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

Hi friends, today we are going to learn how to send Ajax post and get request in MVC.

Let’s get to know What is HTTP Get: If you want to retrieve data from server/client, then we use http get method. In http get only URL and headers are sent to the server. Since, HTTP Get request goes via URL, so it has a limitation for its length. It can’t be more than 255 characters long. In MVC when any view loads for the first time http get method is executed. In Http get data is sent using query string along with the URL. In MVC, we can define [HttpGet] attribute on controller action so the action method can only be accessed via http get method.

Now let’s see What is HTTP Post: If you want to post or send form data to server/client then we use http post method. Http Post method executes once you click on Submit button. The data is included in the body of the request. In MVC we can define [HttpPost] attribute on controller action so the action method can only accessed via http post method.

Similarly there are HTTP PUT and HTTP DELETE methods.

A PUT request is a way to upload a file to a server. Most servers don’t allow PUT requests, because of the security implications.

A DELETE request will delete a resource on the server. Like PUT, this method is rarely permitted on the server for obvious reasons.

So, let’s start with the example. We are using Ajax post and get method in below example.

– Open visual studio then click on file, New Project; Select asp.net MVC web applications and then, Internet Application.

– Now Open Index.cshtml inside View Home Folder and remove all the code and paste the code below in it.

Http get and post

Method Action
Http Get
Click to Get
Http Post
Click to Post

Now open HomeController file inside Controllers folder and add the code below in it

[HttpGet] public ActionResult GetData(string test) { return Json(“Successfully get method executed.”,JsonRequestBehavior.AllowGet); } [HttpPost] public ActionResult PostData(string test) { return Json(“Successfully post method executed.”); }

Now, run the application and see the output.Summary: In above example, we have learnt how to send post and get request using ajax and MVC.

In this article I will explain with an example, how to make a jQuery POST call to Web API 2 Controller’s method using jQuery AJAX in ASP.Net MVC Razor.

What is Web API?

ASP.Net Web API is a framework to build HTTP services which can be consumed by cross platform clients including desktops or mobile devices irrespective of the Browsers or Operating Systems being used.

ASP.Net Web API supports RESTful applications and uses GET, PUT, POST, DELETE verbs for client communications.

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

Web API Controller

In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller.

Now from the Add Scaffold window, choose the Web API 2 Controller – Empty option as shown below.

Then give it a suitable name and click OK.

The next task is to register the Configuration for Web API in the Global.asax file so that the Web API is available for accessing on Web.

In order to do so open Global.asax file and add the following line.

System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);

Make sure you add it in the same order as shown below.

public class MvcApplication : System.Web.HttpApplication

protected void Application_Start()

AreaRegistration.RegisterAllAreas();

System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);

RouteConfig.RegisterRoutes(RouteTable.Routes);

The next step is to code the Web API Controller. The Web API Controller consists of a method named AjaxMethod which accepts an object of PersonModel and updates the DateTime property with the Current Date and Time and returns it back.

This method is decorated with Route attribute which defines its Route for calling the Web API method and HttpPost attribute which signifies that the method will accept Http Post requests.

public class AjaxAPIController : ApiController

[Route(“api/AjaxAPI/AjaxMethod”)]

[HttpPost]

public PersonModel AjaxMethod(PersonModel person)

person.DateTime = DateTime.Now.ToString();

return person;

Controller

Now you will need to add one empty Controller along with a View. The View will be used for calling the Web API 2 Controller’s method using jQuery AJAX.

The Controller consists of an empty Action method which simply returns the View.

public class HomeController : Controller

// GET: Home

public ActionResult Index()

return View();

View

Next step is to add an Empty View without Model for the Controller.

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 call is made to the Web API 2 Controller’s method.

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

@{

Layout = null;

<br /> Index<br />

Screenshot

Downloads

ASP AJAX

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

Example Explained

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

The function is triggered by the onkeyup event.

Here is the HTML code:

Example


Start typing a name in the input field below:

First name:

Suggestions:

Code explanation:

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

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

  • Create an XMLHttpRequest object
  • Create the function to be executed when the server response is ready
  • Send the request off to an ASP file (gethint.asp) on the server
  • Notice that q parameter is added gethint.asp?q=”+str
  • The str variable holds the content of the input field
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!

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?

What is Ajax?

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

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

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

Keywords searched by users: ajax post example 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
Post Form Data To Controller In Asp.Net Mvc Using Ajax - Dotnetxp
Post Form Data To Controller In Asp.Net Mvc Using Ajax – Dotnetxp
Post Data To Controller Using Jquery Ajax In Asp.Net Mvc
Post Data To Controller Using Jquery Ajax In Asp.Net Mvc
Asp.Net Core Mvc Ajax Form Requests Using Jquery-Unobtrusive | Software  Engineering
Asp.Net Core Mvc Ajax Form Requests Using Jquery-Unobtrusive | Software Engineering
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
Mvc Ajax Post Form: Hướng Dẫn Gửi Dữ Liệu Form Với Mvc Và Ajax - Hanoilaw  Firm
Mvc Ajax Post Form: Hướng Dẫn Gửi Dữ Liệu Form Với Mvc Và Ajax – Hanoilaw Firm
Create Ajax Post To Mvc C# - Youtube
Create Ajax Post To Mvc C# – Youtube
Jquery Ajax Call To Mvc Controller With Parameters - Sensible Dev
Jquery Ajax Call To Mvc Controller With Parameters – Sensible Dev
How To Use Ajax With Asp.Net 6 Razor Pages
How To Use Ajax With Asp.Net 6 Razor Pages
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
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
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
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
How To Post Data In Asp.Net Core Using Ajax
How To Post Data In Asp.Net Core Using Ajax
Ajax Calls In Mvc Using Jquery - Youtube
Ajax Calls In Mvc Using Jquery – Youtube
Sử Dụng Jquery Ajax Trong Asp.Net Mvc
Sử Dụng Jquery Ajax Trong Asp.Net Mvc
Github - Codaffection/Jquery-Ajax-With-Asp.Net-Core-Mvc-Using-Modal-Popup
Github – Codaffection/Jquery-Ajax-With-Asp.Net-Core-Mvc-Using-Modal-Popup
Ajax And Jquery In Asp.Net Mvc | Chsakell'S Blog
Ajax And Jquery In Asp.Net Mvc | Chsakell’S Blog
Asp.Net Core: Ajax Form Submit (Post) Example
Asp.Net Core: Ajax Form Submit (Post) Example

See more here: kientrucannam.vn

Leave a Reply

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