Asp.net Using Jquery Ajax Example
In previous post, I have mentioned how to submit form in ASP.NET Core MVC using Tag helpers, now in this article, I have explained how we can submit data to ASP.NET Core MVC (.NET 5) Controller using jQuery AJAX POST method.
Step 1: We will be using Visual Studio 2019 for this, so open your Visual Studio, search select "Create a New Project" and search for "ASP.NET Core MVC web-application" as shown in the below image
Step 2: Select the latest version of .NET Core, that is .NET 5, at the time of writing this article, so I will be using it.
Select Authentication type = None, and Enable Configure for Https
Step 3: Install the Nuget package 'Microsoft.AspNetCore.Mvc.NewtonsoftJson
', as we will be using it, so navigate to Tools -> Nuget Package Manager -> Package Manager Console and use below command
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson
Once package is installed, move to next step.
Step 4: Add the JSON configuration in Startup.cs
Add Reference, 'using Newtonsoft.Json.Serialization;
' and in the 'ConfigureServices
' method use the below code
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddControllers().AddNewtonsoftJson(options => { // Use the default property (Pascal) casing options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); }
We can use other methods for JSON serializer but this method is reliable.
Step 5: Create a new "Student" Model, so right-click on your Models folder and select "Add" then select "Class", once selected type "Student.cs" and use the below code
namespace ASPNETCoreMVCAjax.Models { public class Student { public string Name { get; set; } public string Email { get; set; } } }
Step 6: Navigate to HomeController.cs
and use the code, which will be called when jQuery AJAX method post Data to controller
[HttpPost] public JsonResult AJAXPost(string name, string email) { Student student = new Student { Name = name, Email = email }; //save it in database return Json(student); }
In the above code, we are getting values in POST
method as string parameter from AJAX and just saving it in Student model, I haven't showed how to save it in database, but you can do it using EF Core.
So, your complete HomeController.cs
code will be like below
using ASPNETCoreMVCAjax.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace ASPNETCoreMVCAjax.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { return View(); } [HttpPost] public JsonResult AJAXPost(string name, string email) { Student student = new Student { Name = name, Email = email }; //save it in database return Json(student); } } }
Step 7: Navigate to "Views" -> "Home" -> "Index.cshtml" and use the below code
@{ ViewData["Title"] = "Home Page"; } <div class="text-center"> <input type="text" id="name" name="name" placeholder="Enter Student name" class="form-control" autocomplete="off" /><br/> <input type="text" id="email" name="email" placeholder="Enter Student Email" class="form-control" autocomplete="off" /><br/> <input type="button" value="Post using Ajax" id="post" class="btn btn-primary" /> </div> @section Scripts{ <script type="text/javascript"> $(document).ready(function() { $("#post").click(function () { $.ajax({ type: "POST", url: "/Home/AJAXPost", data: { "name": $("#name").val(), "email": $("#email").val()}, success: function (response) { alert("Student Name: " + response.Name + "<br/>Email: " + response.Email); }, failure: function (response) { alert(response.responseText); }, error: function (response) { alert(response.responseText); } }); }); }); </script> }
In the above view, we are creating 2 input box and a button.
Also, using jQuery AJAX call to submit data to controller, when button is clicked.
In jQuery Ajax method, we have mentioned URL to post data. 'url: "/Home/AJAXPost
"'
Type as POST and data is submitted as 'data: { "name": $("#name").val(), "email": $("#email").val()}
'
that's it, we are done.
Once you will built project and run it in browser you will see output like below
You may also like to read:
File Upload in ASP.NET Core MVC (Single and Multiple)
Form Submit in ASP.NET Core MVC
Model Validation in ASP.NET Core MVC
Creating GridView in ASP.NET Core MVC with Paging
Import Excel data in SQL Server database in ASP.NET Core MVC
Asp.net Using Jquery Ajax Example
Source: https://qawithexperts.com/article/asp-net/sending-data-to-controller-using-jquery-ajax-in-aspnet-core/373
0 Response to "Asp.net Using Jquery Ajax Example"
Post a Comment