I am trying to post html form data to .net core Controller Using Ajax Post. I am storing form data inside a Js Object and sending POST request to Controller using Ajax but I’m getting a null value int the controller object.
HTML Code
<div class="container">
<form id="employeeForm">
<div class="mb-3">
<label asp-for="FullName" class="form-label">Full Name</label>
<input type="text" asp-for="FullName" placeholder="Full Name" class="form-control" required>
<input asp-for="Id" hidden />
</div>
<div class="mb-3">
<label asp-for="Address" class="form-label">Address</label>
<input type="text" asp-for="Address" placeholder="Address" class="form-control" required>
</div>
<div class="mb-3">
<label asp-for="PhoneNo" class="form-label">Phone Number</label>
<input type="text" asp-for="PhoneNo" placeholder="Phone Number" class="form-control" required>
</div>
<div class="mb-3">
<label asp-for="Department" class="form-label"></label>
<input type="text" asp-for="Department" placeholder="Department" class="form-control" required>
</div>
<div class="mb-3">
<a class="btn btn-success" onclick="addEmployee()">Save</a>
<a class="btn btn-danger" asp-controller="Home" asp-action="EmployeeList">Cancel</a>
</div>
</form>
</div>
JS Code
addEmployee = () => {
if ($('#employeeForm').valid()) {
var obj = {
FullName: $('#FullName').val(),
Address: $('#Address').val(),
PhoneNo: $('#PhoneNo').val(),
Department: 0
}
debugger;
$.ajax({
url: '/Home/AddEmployee',
type: 'POST',
contentType: 'application/xxx-www-form-urlencoded;charset=utf-8;',
dataType: 'json',
data: obj,
success: function (res) {
alert(res);
},
});
}
};
C# Controller Code
public class Employee
{
public int Id { get; set; }
public string FullName { get; set; }
public int Department { get; set; }
public string Address { get; set; }
public string PhoneNo { get; set; }
}
[HttpPost]
public JsonResult AddEmployee(Employee obj)
{
return Json("hello");
}
3
Answers
I got the answer removing the contentType in ajax will solve the problem.
This has solved my problem.
You use the incorrect content type, change like below:
I think the problem could be with your js code. According to ASP .NET Core Web API Documentation, you might need change your content type to application/json in order to send Employee object over the wire.
};