ajax - ajax 请求 asp.net mvc 将 id 值从 ajax 请求传递到控制器
问题描述
<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>
}
我正在尝试将视图(JQuery)中找到的 data-id="@item.Id" 值传递给控制器,并使用该值与类的 Id 进行比较。我不确定从 ajax 请求中获取 id 值。
[Route("api/BasketAPI/AddProductToBasket/")]
[HttpPost]
public void AddProductToBasket(int id)
{
var returnAllProductIds = _productService.GetProductsById().Where(X=>X.Id==id).Select(x=>x.Id).FirstOrDefault();
目前,来自 ajax 请求的 id(id 是分配给按钮的产品 id。每个按钮都有一个分配给它的产品 id)没有被传递给控制器。我希望将控制器中方法的参数中的 id 设置为 ajax 请求中的 id。目前尚未设置。
解决方案
请试试这个。
CSHTML 页面
<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>
}
JavaScript 代码
@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;
}
推荐阅读
- python - PyCharm pip install googlesearch 给出错误
- php - 如果重复文件可能具有不同的名称和哈希值,我如何使用 PHP 来检测它们?
- c# - 交换 json 数组索引
- pandas - 索引系列上的 nlargest() 不会返回每个索引的结果
- python-3.x - 通过顺序函数调用更新 tkinter 标签
- sql - 如何合并空列以获取日期范围
- javascript - 请求 rust Rocket 服务器获取来自 JavaScript 应用程序的错误连接被拒绝
- typescript - 如何获得 html data-* 属性的类型安全
- onelogin - Onelogin 通过 API 令牌问题使用会话访问第三方应用程序
- javascript - 如何删除 HTML 表格行