find and solve || findandsolve.com
Please wait.....

POST data using Ajax in asp net Core

Download source code from here
POST data using Ajax in asp net Core

In the article, you will learn with an example, how to submit (post) ViewModel data in Controller using jQuery AJAX in ASP.Net Core with source code. 


Introduction


Post data from View page to Controller is the basic need of any software system. Mostly, if you are using the ASP.Net Core MVC Razor page as frontend then you need to post the form data from view to controller using Ajax post.

In this blog series, you will learn to send the data from the View page to the Controller using the ajax post method in the ASP.NET Core application.


Step 1.


Create New Application in visual studio 2019

  • Open your visual studio 2019 or greater than 2019
  • Click on Create a New Project
  • Select ASP.NET Core Web Application and then Next
  • Provide a Project name and confirm or change the Location. Select Create
  • Select the latest version of ASP.NET Core in the drop-down (.NET Core 5.0)and then select Web Application
  • Under Authentication, select Change and set the authentication to Individual User Accounts and then click on Create button



Step 2.


Go to your HomeController(as we have been using a basic template, not an empty MVC project), and create a new action method Create like as given below.

public IActionResult Create()
{
    return View();
}


Step 3.


Add ViewModel

Once it is created new project, then you will add the model StudentInfoViewModel.cs. Click on the Models folder and add a new class named as StudentInfoViewModel.cs as depicted given below.




You will use four sample fields for form submission, so add four properties in the StudentInfoViewModel.cs. Write below the line of code in this class:

namespace PostDataUsingAjax.Models
{
    public class StudentInfoViewModel
    {
        public int StudentId { get; set;}
        public string FirstName { get; set; }
        public string LastName { get; set;}
        public string Address { get; set;}
    }
}


Step 4.


Right-Click inside the above created ActionMethod and Click on "Add View" like as given below.



When you click on Razor View-Empty you will see like as given below




Step 5.


Place this code in your created view page (Create.cshtml) like as given below.

@model PostDataUsingAjax.Models.StudentInfoViewModel
@{
    ViewBag.Title = "Create";
}
<div class="container">
    <div class="container-fluid">
        <div class="row">
            <div class="col-sm-5 offset-sm-3">
                <form id="studentInfoId">
                    @Html.AntiForgeryToken()
                    <span class="alert-danger">
                        @Html.ValidationSummary(true)
                    </span>
                    <div class="form-group">
                        <label>Student ID</label>
                        <input asp-for="StudentId" class="form-control" />
                        <span asp-validation-for="StudentId" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <label>First Name</label>
                        <input asp-for="FirstName" class="form-control" />
                        <span asp-validation-for="FirstName" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <label>Last Name</label>
                        <input asp-for="LastName" class="form-control" />
                        <span asp-validation-for="LastName" class="text-danger"></span>
                    </div>
                    <div class="form-group">
                        <label asp-for="Address"></label>
                        <input asp-for="Address" class="form-control" />
                        <span asp-validation-for="Address" class="text-danger"></span>
                    </div>
                    <div class="modal-footer">
                        <input type="button" class="btn btn-primary" value="Summit" onclick="post()" />
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>


Then, you will use the below javascript on the form submission button click event using Ajax in Create.cshtml page.

@section scripts{
    <script type="text/javascript">
        var post = function () {
            var data = $("#studentInfoId").serialize();         
            $.ajax({
                type: "POST",
                url: "/Home/Create",
                data: data,// $('#studentInfoId').serialize(),
                contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                success: function (response) {
                    alert("Hello")
                },
                 error: function () {
                    alert('Failed to receive the Data');
                    console.log('Failed ');
                }
            });
        };
    </script>
}


Here, you have used form serialization. The below line is for the Form serialization method.

$("#studentInfoId").serialize();


Step 6.


Add post method in Home Controller for Submit button click Event

Then you will write the Post method in HomeController for the Form Submit event. Here is the code of the HTTP post method in HomeController with Model validation.

        [HttpPost]
        public IActionResult Create(StudentInfoViewModel model)
        {
            if (ModelState.IsValid)
            {
                return Json("Request Success");
            }
            return Json("Request Failed");
        }


Now, build the project and run and fill all the fields, Submit the form, debug and check whether the data is passed to the controller or not.


How to Post data using Pop Up Modal using Ajax in .net core?

CRUD in ASP.NET Core using Angular

CRUD Application In asp.net Core 3.1 || Entity Framework Code First

Uploading File using Ajax in Asp.Net Core

Cascading DropDownList In .NET Core

Mahira  khanna

Mahira khanna

I have the skills you need for you company blog, website, or other content materials

Comments



Report Response