Here is the product class:
public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
[Required]
[Range(1, 1000000)]
public decimal Price { get; set; }
[Required]
public string Category { get; set; }
}
Here is my .cshtml page:
<div class="alert alert-success">
<span id="responseMessage"></span>
</div>
<div class="form-group">
<label>Name</label>
@Html.TextBoxFor(x => x.Name)
</div>
<div class="form-group">
<label>Price</label>
@Html.TextBoxFor(x => x.Price)
</div>
<div class="form-group">
<label>Category</label>
@Html.TextBoxFor(x => x.Category)
</div>
<div class="form-group">
<label>Description</label>
@Html.TextBoxFor(x => x.Description)
</div>
<button id="postButton">Ok</button>
Here is my javascript:
$(document).ready(function () {
$("#postButton").click(function () {
var product = 'product=' +
JSON.stringify({
Name: $('#Name').val(),
Description: $('#Description').val(),
Price: $('#Price').val(),
Category: $('#Category').val()
});
$.ajax({
url: "/api/products/postproduct",
type: "POST",
data: product,
dataType: 'json',
success: function (data, status, xhr) {
$('#responseMessage').html('Insert status: ' +
data.d.status);
},
error: function (xhr, status, error) {
alert('Error occurred: ' + status);
}
});
});
});
Here is my controller:
public async Task<IHttpActionResult> PostProduct(Product product)
{
if (ModelState.IsValid)
{
await Repository.SaveProductAsync(product);
return Ok();
}
else
{
return BadRequest(ModelState);
}
}
Thank you in advance. The ajax post hits the controller ( i set a breakpoint there), but when i hover over the product parameter there are no values coming in. Let me know if you need any more information.