I am trying to implement a product information window in which there is a partial view responsible for displaying the quantity of product in stock. The quantity of the product in stock is represented by a separate linked table "productCount". I need to add the product quantity without reloading the view and reload only a partial view. To do this, I decided to use jQuery AJAX. The solution method was based on the materials of this answer: "link". But I ran into problems unknown to me.: Firstly, I have difficulty getting the value from the input field, and secondly, when I try to execute the function, a message unknown to me appears Script code:
<script type="text/javascript">
function addQuantityClicked() {
var Url = '@Url.Action("QuantityAdd", "Home")';
$.ajax({
url: Url,
type: 'POST',
data: { idProduct: @Model.Product.Id, quantity: alert($("#qnt").val) }
})
}
</script>
@using vp_server.Models.ViewModels
@model vp_server.Models.ViewModels.ProductViewsTransactions
<!DOCTYPE html>
<html>
<body>
<label>The quantity at the moment: @Model.Count</label>
<form>
<label>Entrance:</label>
<input type="number" id="qnt" name="quantity" />
<input type="button" onclick="addQuantityClicked()" id="changeButton" value="Add" />
</form>
</body>
</html>
<script src="~/js/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/js/jquery-3.5.1.min.js"></script>
I also tried to use document.getElementById("qnt").value
but.value
is not defined by the code editor
Strange message when trying to execute the script The code of the controller method:
[HttpPost]
public async Task<IActionResult> QuantityAdd(int idProduct, int quantity)
{
using (VapeshopContext db = new VapeshopContext())
{
ProductCount? productCount = db.ProductCounts.Where(pc => pc.ProductId == idProduct).FirstOrDefault();
if (productCount != null)
{
productCount.Count += quantity;
}
await db.SaveChangesAsync();
return PartialView();
}
}
I deleted the alert, although now the message does not appear, but the method also does not respond
I partially changed the JS code and removed .ajax to test the script and left a test message in .alert
. The message is output, but if you return .ajax
, nothing happens and even the message is output to .alert
New JS code:
<script type="text/javascript">
$(function () {
$("#btnPost").click(function () {
alert("Test")
$.ajax({
type: "POST",
url = "/Home/QuantityAdd",
data: { "idProduct": @Model.Product.Id, "quantity": $("#qnt").val() }
})
})
})
</script>
<script src="~/js/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/js/jquery-3.5.1.min.js"></script>
I test your code like:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script type="text/javascript">
function addQuantityClicked() {
var Url = '@Url.Action("QuantityAdd", "Home")';
$.ajax({
url: Url,
type: 'POST',
data: { "idProduct": 1, "quantity":2 }
});
}
</script>
result: