We want to pass some data from jQuery to ASP.NET Core / MVC. We have an action method “AddEmployee” in Home controller and we want to pass input values to the controller.
$(document).ready(function () {
$("#btnSave").click(function () {
var formData = new FormData();
//Reading text box values using Jquery)
formData.append('Name', $("#txtName").val();
formData.append('City',$("#txtAddress").val());
formData.append('Address',$("#txtcity").val());
$.ajax(
{
type: "POST", //HTTP POST Method
url: "Home/AddEmployee", // Controller/View
//url: '@Url.Action("AddEmployee", "Home")',
data: { //Passing data
formData
},
//cache: false,
//processData: false,
//contentType: false,
success: function (data) {
alert("success...any incoming data");
},
failure: function (data) {
alert("failure....");
}
});
});
});
Alternatively we can have seperate functions for success and failure actions;
function btnSaveSuccess(data)
{
alert('success');
}
function btnSaveFailure(data)
{
alert('failure');
}
We can call these functions in btnSave main function sucess/failure blocks.
To work with jQuery we need to reference of jQuery library .You can use following CDN jQuery libraryfrom any provider such as Microsoft,Google or jQuery .
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
To use jQuery library you need an active internet connection , You can download and use it as offline .You need to be add reference as like below.
<script src="~/Scripts/jquery-1.10.2.min.js"></script>