How To Post Data In ASP.NET Using AJAX Form Serialization

Table of Contents

Welcome to mycodebit. When we work with ASP.NET (Core) MVC we have to submit the forms through razor pages so, in this article, we discuss How To Post Data In ASP.NET Using AJAX Form Serialization. I’m using visual studio 2019 for this tutorial.

If you have not created the project yet please follow this link to create a new project.

Steps:

Let’s first create a model that we will use to submit the form data and we will create this model class as per our requirement to transfer data.

public class SubmitPersonalInfo
    {
        public string Name { get; set; }
        public string Gender { get; set; }
        public string Age { get; set; }
        public string Height { get; set; }
    }

I have created a model class with the name “SubmitPersonalInfo” with the required fields that I want to submit.

I’m creating a page for submitting this specific information.

Post Data In ASP.NET Using AJAX

After Clicking on View you will have a screen like this.

Post Data In ASP.NET Using AJAX

Click on Add after selecting “Razor View – Empty”. and after clicking on Add give a name to your page and Add the page.

Post Data In ASP.NET Using AJAX

After adding the page add the action method to return the view from the controller.

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

Do not forget to add the page link to the home page. Open “_Layout.cshtml” and paste.

<li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp -action="PersonalInfo">Personal Info</a>
                        </li>

In the asp-controller tag give the name of your controller and in the asp-action give the name of your action method as I did.

Now let’s add the form fields that we want to submit. Paste this HTML code into your razor view page that we created.

@model SubmitPersonalInfo
<h4>Submit Personal Information</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form id="personalInfo" novalidate class="needs-validation">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" type="text" class="form-control" id="name" required />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Age" class="control-label"></label>
                <input asp-for="Age" type="number" class="form-control" id="age" />
                <span asp-validation-for="Age" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Gender" class="control-label"></label>
                <input asp-for="Gender" type="text" class="form-control" id="gender" />
                <span asp-validation-for="Gender" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Height" class="control-label"></label>
                <input asp-for="Height" type="number" class="form-control" id="height" />
                <span asp-validation-for="Height" class="text-danger"></span>
            </div>
            <div class="form-group">
                <button type="button" class="btn btn-primary" onclick="submitPersonalInfo()">Submit</button>
            </div>
        </form>
    </div>
</div>

You can see that I have imported the model at the top of the page and used its properties in the form. If we do not import the data model the page will give the runtime error.

Let’s have look at our Javascript code snippet.

<script type="text/javascript">
    function submitPersonalInfo() {
        var data = $("#personalInfo").serialize();
        console.log(data);
        alert(data);
        $.ajax({
            type: 'POST',
            url: '/Home/SubmitInfo',
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8', // when we use .serialize() this generates the data in query string format. this needs the default contentType (default content type is: contentType: 'application/x-www-form-urlencoded; charset=UTF-8') so it is optional, you can remove it
            data: data,
            success: function (result) {
                alert('Successfully received Data ');
                console.log(result);
            },
            error: function () {
                alert('Failed to receive the Data');
                console.log('Failed ');
            }
        })
    }

</script>

In this script you can see in the data variable I have used my form id “personalInfo” and serialized all my data into the string format. After that, I have provided the Url of my controller action “url: ‘/Home/SubmitInfo'”.

Lets see the controller action that I have created in the home controller.

[HttpPost]
        public async Task<IActionResult> SubmitInfo(SubmitPersonalInfo info)
        {
            if (!ModelState.IsValid) return BadRequest("Enter required fields");
            //Write your Insert code here;
            return this.Ok("Form Data received!");
        }

You can see the controller action type is post and our ajax is also post.

Complete the code of the razor view page.

@model SubmitPersonalInfo

@{
    ViewData["Title"] = "Personal Information";
}

<script type="text/javascript">
    function submitPersonalInfo() {
        var data = $("#personalInfo").serialize();
        console.log(data);
        alert(data);
        $.ajax({
            type: 'POST',
            url: '/Home/SubmitInfo',
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8', // when we use .serialize() this generates the data in query string format. this needs the default contentType (default content type is: contentType: 'application/x-www-form-urlencoded; charset=UTF-8') so it is optional, you can remove it
            data: data,
            success: function (result) {
                alert('Successfully received Data ');
                console.log(result);
            },
            error: function () {
                alert('Failed to receive the Data');
                console.log('Failed ');
            }
        })
    }

</script>

<h4>Submit Personal Information</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form id="personalInfo" novalidate class="needs-validation">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" type="text" class="form-control" id="name" required />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Age" class="control-label"></label>
                <input asp-for="Age" type="number" class="form-control" id="age" />
                <span asp-validation-for="Age" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Gender" class="control-label"></label>
                <input asp-for="Gender" type="text" class="form-control" id="gender" />
                <span asp-validation-for="Gender" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Height" class="control-label"></label>
                <input asp-for="Height" type="number" class="form-control" id="height" />
                <span asp-validation-for="Height" class="text-danger"></span>
            </div>
            <div class="form-group">
                <button type="button" class="btn btn-primary" onclick="submitPersonalInfo()">Submit</button>
            </div>
        </form>
    </div>
</div>

Here are the working results of the code.

Post Data In ASP.NET Using AJAX

By using a debugger we can see the data.

Post Data In ASP.NET Using AJAX

Conclusion:

If you face any issue or problem using this tutorial or have any suggestions to make our content better please do not hesitate to comment below or contact us.

Leave a Reply

Your email address will not be published.