Hi santos,
Refer below example.
Model
public class EmployeeModel
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
public Int64 ContactNo { get; set; }
}
Controller
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult AjaxMethod(EmployeeModel employee)
{
EmployeeModel person = new EmployeeModel
{
Name = employee.Name,
Age = employee.Age,
Address = employee.Address,
ContactNo = employee.ContactNo
};
return Json(person);
}
}
View
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form>
@Html.AntiForgeryToken()
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="txtName" /></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" id="txtAge" /></td>
</tr>
<tr>
<td>Address:</td>
<td><input type="text" id="txtAddress" /></td>
</tr>
<tr>
<td>Contact No:</td>
<td><input type="text" id="txtContactNo" /></td>
</tr>
<tr>
<td colspan="2"><input type="button" id="btnSubmit" value="Submit" /></td>
</tr>
</table>
<hr />
<table>
<tr>
<td>Name:</td>
<td><label id="lblName" /></td>
</tr>
<tr>
<td>Age:</td>
<td><label id="lblAge" /></td>
</tr>
<tr>
<td>Address:</td>
<td><label id="lblAddress" /></td>
</tr>
<tr>
<td>Contact No:</td>
<td><label id="lblContactNo" /></td>
</tr>
</table>
</form>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnSubmit").click(function () {
var employeeObj = {};
employeeObj.Name = $("#txtName").val();
employeeObj.Age = $("#txtAge").val();
employeeObj.Address = $("#txtAddress").val();
employeeObj.ContactNo = $("#txtContactNo").val();
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: {
__RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
employee: employeeObj
},
success: function (response) {
$("#lblName").html(response.Name);
$("#lblAge").html(response.Age);
$("#lblAddress").html(response.Address);
$("#lblContactNo").html(response.ContactNo);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
</body>
</html>