This is my code for my form:
<div class="form-group">
<label for="text">product name:</label>
<input id="name" type="text" class="form-control" placeholder="Enter product name" name="product[0].name">
</div>
<div class="form-group">
<label for="text">product detail:</label>
<input id="detail" type="text" class="form-control" placeholder="Enter prodcut detail" name="product[1].detail">
</div>
<button id="btn" type="submit" class="btn btn-default">Submit</button>
This is my javascript
<script>
$(function postProduct() {
$('#btn').click(function () {
var productName = document.getElementById("name").value;
var productDetail = document.getElementById("detail").value;
var dimensions = [ productName, productDetail];
var keys = $.map(dimensions, function (value, key) {
return key;
});
if (productName == '' || productDetail == '') {
alert("Please Fill All Fields");
} else {
$.ajax({
type: 'post',
url: "api/product/addproduct",
data: keys,
dataType: 'json',
success: function (result) {
},
error: function (error) {
}
});
}
});
});
</script>
My controller:
[HttpPost]
[Route("api/product/addproduct")]
public IActionResult AddProduct([FromBody] string[] addproduct)
{
var pProductName= addProduct[0];
var pProductDetail= addProduct[1];
Product NewProduct = new Product();
{
NewProduct.ProductName= pProductName;
NewProduct.ProductDetail = pProductDetail;
}
_db.Products.Add(NewProduct);
_db.SaveChanges();
//create a new route for post method by id
return CreatedAtRoute(new { id = addproduct}, addproduct);
}
What I'm trying to do is after the user enters the information into the form and hits submit button. The information will be pass to the controller and save the information into the database. The issue that I have is my data in the form is a Json type, however, my controller is an array.
Is it possible to convert the form into an array?