Skip to content
Home » Ajax Post In Mvc | Http Request: Getpost

Ajax Post In Mvc | Http Request: Getpost

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

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

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.

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

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!

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

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!

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.

jQuery – AJAX get() and post() Methods

The jQuery get() and post() methods are used to request data from the server with an HTTP GET or POST request.

jQuery $.post() Method

The

$.post()

method requests data from the server using an HTTP POST request.

Syntax:

The required URL parameter specifies the URL you wish to request.

The optional data parameter specifies some data to send along with the request.

The optional callback parameter is the name of a function to be executed if the request succeeds.

The following example uses the

$.post()

method to send some data along with the
request:

Example

$.post(“demo_test_post.asp”,

name: “Donald Duck”,

city: “Duckburg”

},

function(data, status){

alert(“Data: ” + data + “\nStatus: ” + status);

});

});

The first parameter of

$.post()

is the URL we wish to request (“demo_test_post.asp”).

Then we pass in some data to send along with the request (name and city).

The ASP script in “demo_test_post.asp” reads the parameters, processes them, and returns a result.

The third parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.

Tip: Here is how the ASP file looks like (“demo_test_post.asp”):

dim fname,city

fname=Request.Form(“name”)

city=Request.Form(“city”)

Response.Write(“Dear ” & fname & “. “)

Response.Write(“Hope you live well in ” & city & “.”)

%>

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

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.

HTTP Request: GETPOST

Two commonly used methods for a request-response between a client and server are: GET and POST.

  • GET – Requests data from a specified resource
  • POST – Submits data to be processed to a specified resource

GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data.

POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.

To learn more about GET and POST, and the differences between the two methods, please read our HTTP Methods GET vs POST chapter.

Create ajax post to MVC C#
Create ajax post to MVC C#

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.

Ajax Call Getting started

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

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

jQuery $.get() Method

The

$.get()

method requests data from the server with an HTTP GET request.

Syntax:

The required URL parameter specifies the URL you wish to request.

The optional callback parameter is the name of a function to be executed if the request succeeds.

The following example uses the

$.get()

method to retrieve data from a file on
the server:

Example

$.get(“demo_test.asp”, function(data, status){

alert(“Data: ” + data + “\nStatus: ” + status);

});

});

The first parameter of

$.get()

is the URL we wish to request (“demo_test.asp”).

The second parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.

Tip: Here is how the ASP file looks like (“demo_test.asp”):

response.write(“This is some text from an external ASP file.”)

%>

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

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

Hi,

Are you using submit button , type = submit or type = button.

type = button

may solve it

Regards.

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Hello

I am developing an Asp.net Core Mvc application in which I need to send , as usual, some data from an ajax call to an MVC action. The ajax code is as follows :


**function ShowHideAttivita(model, idriga) { var dati =model; var idcommessa = $('#IdselectCommessa' + idriga + ' option:selected').val(); $.ajax({ url: 'cambiaCommessa', type: 'POST', dataType: "html", contentType: "application/json", data: dati, success: function (result) { $('#IdrigaSezioneCommessa' + idriga).replaceWith(result); }, error: function (error) { var x = error.responseText; VisualizzaMessaggio('errore', 'E', ''); } }); }**

The corresponding MVC Controller Action which is listening is as follows ;


**[HttpPost] public async Task

cambiaCommessa( RapGiornalieroExtended dati) { try { DettaglioPresenze DP = new DettaglioPresenze(); return PartialView("~/Views/Home/_rigaCommessa.cshtml", DP); } catch (Exception ex) { throw ex; } }**

It seems I can call the action correctly, but the content in the data sent is null (the fields of the “dati” parameters).No matter how I change the code in the sending Ajax, when I break into the Action , the best result I can get is getting a “dati” parameter (which is a complex type itself) with all its fields null, in spite of the fact that, in the sending ajax, i verified the content is not null. Most inquietingly, another application from which this same bunch of code is taken works perfectly , and there are no differences in the Ajax, in the Controller, in the Action, and in the data content itself, between the two situations.

Any suggestions ? Thanks

What is the “model” of 1st argument in the ShowHideAttivita method? What is the RapGiornalieroExtended class in the cambiaCommessa method?

Have you seen what are sent and received between the client and server by using a capture toll such as the Fiddler and confirmed the header and contents are proper as expected?

I didn’t check the post header, but I am 100% sure that the “model” parameter is correctly set. It is a js version of the RapGiornalieroExtended object which is the parameter expected by the action. This object (class) is made up of three member the first of which is another class, and the second and third are respectively a list of objects and a dictionary of strings.Both the list and dictionary members contain values , the first member which is a scalar object is a null reference.What i expect on the action side is to receive the same values but I verified instead that all the three members are null references.

Actually, as I verified yesterday after posting this question, is seems the data : …. parameter of the ajax call is ignored, since as I remove it nothing changes in the action behavior.

Do you think I should check the post header ?

By checking the post header I see that, in spite of the fact that I set the ajax call’s content-Type parameter to “application/json”, in the header I end up having , from time to time , “application/www-url-encoded” … but as I said this is not sistematic, this just happens randomly. Anyway, no matter what content-Type is set, I always have, in the action parameter, an object with all the three members having null references.

Have you seen what are sent and received between the client and server by using a capture toll such as the Fiddler and confirmed the header and contents are proper as expected?

In your jQuery ajax code you include contentType: “application/json”. It means that the server must receive JSON string.

You say that the dati (= model) is “js version of the RapGiornalieroExtended object.” But the javascript object will be converted to application/x-www-form-urlencoded format, not JSON.

I don’t have any capture toll and am not allowed to install since my laptop belongs to the company. All I can say is that, checking from the Web Browser debugger, the request payload is what I expect it to be (most of the times but not always).I am not sure I get you when you say that “the object will be converted to “application/x-www-form-urlencoded” : is this by default ?and in case, this means that I should do something like :

…. data : JSON.strinfigy(dati),….

????

If yes, this is a solution I already attempted and didn’t work either…

IE, Chrome. Edge, Firefox has tool to capture the request and response. You have to use it to see what’s going on between the client and server. You can’t shoot in the dark.

Please read the jQuery API documentation.

jQuery.ajax()

See “data” section. It describes that:

When data is an object, jQuery generates the data string from the object’s key/value pairs unless the processData option is set to false. For example, { a: “bc”, d: “e,f” } is converted to the string “a=bc&d=e%2Cf”.

Note that “a=bc&d=e%2Cf” is not JSON string.

You said you have already tried JSON.strinfigy(dati) but it does not work. I don’t know why. But at least I am sure that you have to send JSON string to the server which expects to receive JSON string.

Hi @LeoDelCiello-425, please check the actual request and posted data that you made from ajax client in browser F12 developer tool Network tab. And if possible, you can share the details about request headers and payload, so that we can help troubleshoot the issue better. Besides, you can try to apply

[FromBody]

attribute to your action parameter, like this

public async Task

cambiaCommessa([FromBody]RapGiornalieroExtended dati)


.

Hi,

Are you using submit button , type = submit or type = button.

type = button

may solve it

Regards.

Cách sử dụng Ajax trong ASP.NET MVC 5 phần 1 (CRUD using Ajax in ASP.NET MVC)
Cách sử dụng Ajax trong ASP.NET MVC 5 phần 1 (CRUD using Ajax in ASP.NET MVC)

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.

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

FULL MATCH: MÃ Minh Cẩm - Frederic CAUDRON | Bán Kết PBA - Silkroad & Ansan PBA Championship 23-24
FULL MATCH: MÃ Minh Cẩm – Frederic CAUDRON | Bán Kết PBA – Silkroad & Ansan PBA Championship 23-24

Keywords searched by users: ajax post in mvc

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
Post Form Data To Controller In Asp.Net Mvc Using Ajax - Dotnetxp
Post Form Data To Controller In Asp.Net Mvc Using Ajax – Dotnetxp
Create Ajax Post To Mvc C# - Youtube
Create Ajax Post To Mvc C# – Youtube
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 Data To Controller Using Jquery Ajax In Asp.Net Mvc
Post Data To Controller Using Jquery Ajax In Asp.Net Mvc
Posting Javascript Types To Mvc 6 In .Net Core, Using Ajax | I Came, I  Learned, I Blogged
Posting Javascript Types To Mvc 6 In .Net Core, Using Ajax | I Came, I Learned, I Blogged
40) Post Data Using Ajax In Mvc | Asp.Net Mvc 5 Tutorial-Step By Step In  Hindi - Youtube
40) Post Data Using Ajax In Mvc | Asp.Net Mvc 5 Tutorial-Step By Step In Hindi – Youtube
Ajax Post In Asp.Net Mvc - Youtube
Ajax Post In Asp.Net Mvc – Youtube
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
Asp.Net Core: Ajax Form Submit (Post) Example
Asp.Net Core: Ajax Form Submit (Post) Example
Render Partialview Using Jquery Ajax In Asp.Net Mvc – Srinivasaraju'S Blog
Render Partialview Using Jquery Ajax In Asp.Net Mvc – Srinivasaraju’S Blog
Jquery Ajax Call To Mvc Controller With Parameters - Sensible Dev
Jquery Ajax Call To Mvc Controller With Parameters – Sensible Dev
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
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
Data Editors For Asp.Net Mvc - How To Use Ajax Callbacks To Validate A  Captcha Code And Submit A Form | Devexpress Support
Data Editors For Asp.Net Mvc – How To Use Ajax Callbacks To Validate A Captcha Code And Submit A Form | Devexpress Support
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
Asp.Net Mvc - Loading Partial Views Using Ajax/Jquery - Youtube
Asp.Net Mvc – Loading Partial Views Using Ajax/Jquery – Youtube
Crud Using Ajax In Asp.Net Mvc - Tuấn
Crud Using Ajax In Asp.Net Mvc – Tuấn
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

See more here: kientrucannam.vn

Leave a Reply

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