Hello when i use Post methode using Web API i was not able to add it to database.
I used Jquery to call api POST METHODE
While using postman i was able to post some data to database.
I guess the problem in the view or in the Jquery. Any help please
MVC CONTROLLER
public ActionResult New(Customers customers)
{
return View(customers);
}
API CONTROLLER FOR POST
[HttpPost]
public IHttpActionResult CreateCustomer(Customers CustomerDTO)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
_context.Customerss.Add(CustomerDTO);
_context.SaveChanges();
return Created(new Uri(Request.RequestUri + "/" + CustomerDTO.Id), CustomerDTO);
}
VIEW
@model API.Models.Customers
@{
ViewBag.Title = "New";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>New Form</h2>
<div id="container">
<form>
<div class="form-group" id="NameGroup">
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name, new { @class = "form-control", id = "Name" })
</div>
<button type="submit" class="btn btn-primary js-Add">Save</button>
</form>
</div>
@section scripts {
<script type="text/javascript">
$(document).ready(function () {
$("#container .js-Add").on("click", function (e) {
e.preventDefault();
if (confirm("Are you sure you want to ADD this customer?")) {
var input = $("Name").val();
$.ajax({
url: "../api/Customer",
type: "POST",
data: JSON.stringify(input),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert('HELLO' + response.Name);
}
});
}
});
});
</script>
}
CLASS CUSTOMER
public class Customers
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
ANY HELP PLEASE OR ANY ADVISE THANK YOU!!