Post form data to controller in ASP.NET MVC using Ajax

How to post form data to controller using Ajax in ASP.NET MVC (using Jason form serialization)

Sometimes we have to use ajax post to send the data from the view to controller. In this article I’m going to create a simple data entry form and post form data to the controller action.

Below is the sample screen and using this I’m posting 3 data fields from view to the controller using model and display a success message. In here we have a “Create” button and “Save Draft” button. Here we cant use the traditional form submit method to post form data to controller since we have two submit buttons. We can use normal form submission only for one button inside the form. To save as a draft we have to use an Ajax post to call the controller and post data to controller.

Screen

First I have added a new controller “UserController” and implemented the methods to create a new user. Basically I added the Create Get method and create Post method.

Then I added a new Model for user entity with three fields.

The next step is to add a new view for the create method. Here I have used the MVC Create template and also used the UserViewModel class as the Model class. So MVC will automatically create the view to match the entity.

Here is the auto generated view.

@model AjaxPost.Models.UserViewModel

@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
<h4>UserViewModel</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}

At this step we can run the project and submit the data to create a user  but still this is a normal post and we didnt use ajax post yet.

After submitting the form we can see the posted data in the controller by using the debugger.

Still this is just a usual form post and then we can add a new button to Save as draft.

Adding a new button

<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
<input type="button" value="Save Draft" class="btn btn-warning" id="btnDraft" />
</div>
</div>

Then we have to add the ajax calls in the script. So I have added a new javascript file to the project (If you are new to this topic please refer this article).

Then add the controller method to get the posted data from the ajax call. SaveDraft post method created with UserViewModel as a parameter. Now our challenge is to retrieve posted form data in this action.

We should modify the javascript file to handle the newly added Save Draft button click and when a user click on this button we have to read the form data and post form data to the controller.

So I added some jquery methods to post form data. First we serialize the form data and post form data to the controller as an Ajax post.

custom script file

$("#btnDraft").click(function () {
$.ajax({
url: 'SaveDraft',
type: 'POST',
data: JSON.stringify($("#createuserform").serializeObject()),
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
if (data != null && data.Success) {
alert(data.Message);
} else {
// DoSomethingElse()
alert(data.Message);
}
},
error: function (data) {
alert("error!"); //
}
});
});

$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};

Bravo ! Now we have implemented the functionality and the next part is to test the application.

Now run the application, fill the form data and click on the Save Draft button ! and dont forget to set a break point for the SaveDraft method.

Created page :

In the debug mode we can see the entered data already bound to the model by the MVC Model Binder.

Finally we can see the success message.

This covers the basic functionality to post form data to controller using ajax call and still valid with new .NET 5 also.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.