ajax请求asp.net mvc将id值从ajax请求传递给控制器
目前,来自ajax请求的id(该id是分配给按钮的产品id。每个按钮都有分配给它的产品id)没有传递给控制器。我希望控制器中方法的参数中的id设置为ajax请求中的id。目前尚未设置此选项。请尝试此选项 CSHTML页面ajax请求asp.net mvc将id值从ajax请求传递给控制器,ajax,asp.net-mvc,asp.net-ajax,Ajax,Asp.net Mvc,Asp.net Ajax,目前,来自ajax请求的id(该id是分配给按钮的产品id。每个按钮都有分配给它的产品id)没有传递给控制器。我希望控制器中方法的参数中的id设置为ajax请求中的id。目前尚未设置此选项。请尝试此选项 CSHTML页面 为什么是h.id?!因为您已经在数据Id属性中设置了@item.Id。在Ajax中使用此选项:data:{id:$(this).attr(“data id”)}和contentType:“application/json;charset=utf-8”,。您可能需要在您的 Add
为什么是h.id?!因为您已经在
数据Id
属性中设置了@item.Id
。在Ajax中使用此选项:data:{id:$(this).attr(“data id”)}
和contentType:“application/json;charset=utf-8”,
。您可能需要在您的<代码> AddioToToToBase/CudioAction方法中考虑ID为字符串。您是否在控制台中检查了任何错误?
<h2>GetAllProducts</h2>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Genre)
</th>
<th>
@Html.DisplayNameFor(model => model.AgeId)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
@Html.DisplayFor(modelItem => item.AgeId)
</td>
<td> <button type="button" data-id="@item.Id"
class="productIdButton">AddProductToBasket</button></td>
</tr>
}
@section scripts {
<script type="text/javascript">
$("button").click(function () {
//returns all the product ids
//want to return the selected id of the button clicked
// var h = ($(this).data("id"));
var h= ($(this).attr("data-id"));
var productId = (h.Id);
var s = productId;
//alert(productId);
$.ajax({
url: "/api/BasketAPI/AddProductToBasket/",
type: "POST",
data: { id: productId },
contentType: false,
cache: false,
processData: false,
});
});
</script>
[Route("api/BasketAPI/AddProductToBasket/")]
[HttpPost]
public void AddProductToBasket(int id)
{
var returnAllProductIds = _productService.GetProductsById().Where(X=>X.Id==id).Select(x=>x.Id).FirstOrDefault();
<h2>GetAllProducts</h2>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Genre)
</th>
<th>
@Html.DisplayNameFor(model => model.AgeId)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
@Html.DisplayFor(modelItem => item.AgeId)
</td>
<td> <button type="button" onclick="AddProductToBasket(@item.Id)" data-id="@item.Id"
class="productIdButton">AddProductToBasket</button></td>
</tr>
}
@section scripts {
<script type="text/javascript">
function AddProductToBasket(productid)
{
try
{
$.ajax({
url: "/api/BasketAPI/AddProductToBasket",
type: "POST",
data: { id: productid },
success: function(oData){
alert(oData);
},
error:function(error)
{
alert(error);
}
});
}
catch(e)
{
alert(e.message);
}
}
</script>
}
[Route("api/BasketAPI/AddProductToBasket/")]
[HttpPost]
public int AddProductToBasket(int id)
{
var returnProductId = _productService.GetProductsById().Where(X=>X.Id==id).Select(x=>x.Id).FirstOrDefault();
return returnProductId;
}