Jquery MVC异步Ajax调用
我正在一个电子商务网站上工作,我有以下模板:Jquery MVC异步Ajax调用,jquery,asp.net,ajax,asp.net-mvc,asp.net-mvc-4,Jquery,Asp.net,Ajax,Asp.net Mvc,Asp.net Mvc 4,我正在一个电子商务网站上工作,我有以下模板: <div class="product-box"> Product 1 </div> <div class="product-box"> Product 2 </div> <div class="product-box"> Product 3 </div> 该网站是ASP.NET MVC,我想使用jQuery ajax调用我的MVC控制器,异步地用产
<div class="product-box">
Product 1
</div>
<div class="product-box">
Product 2
</div>
<div class="product-box">
Product 3
</div>
该网站是ASP.NET MVC,我想使用jQuery ajax调用我的MVC控制器,异步地用产品信息填充不同的产品框,最好的方法是什么
我已经能想到这样的事情了
<div id="product1" class="product-box">
Product 1
</div>
<div id="product2" class="product-box">
Product 2
</div>
<div id="product3" class="product-box">
Product 3
</div>
<script>
$.get("/GetProductInfo/1", {}, function (data) {
$("#product1").html(data);
});
$.get("/GetProductInfo/2", {}, function (data) {
$("#product2").html(data);
});
$.get("/GetProductInfo/3", {}, function (data) {
$("#product3").html(data);
});
</script>
但这毫无意义,也不是最好的方法。想象我有1000种产品,疯狂。任何人都可以为我提供最好的建议吗?您可以尝试以下方法:
HTML:
您可以使用data-*属性提供产品编号,如:
<div data-id="1" class="product-box">
<div data-id="2" class="product-box">
<div data-id="3" class="product-box">
.......
// more
您可以使用纯ASP.NET MVC和 调用指定的子操作方法并在父视图中内联呈现结果 示例代码:
@{Html.RenderAction("GetProductInfo", "YourController", new { id: YourProductId });}
如果您想使用jQuery执行相同的操作,我建议您使用自定义数据前缀属性来存储产品id
下面是一个使用和的示例
HTML
是什么触发了将细节加载到div中?如果希望一次加载所有项目,为什么不返回一个显示所有项目详细信息(包括div)的视图呢。
@{Html.RenderAction("GetProductInfo", "YourController", new { id: YourProductId });}
<div data-productid="1" class="product-box">
Product 1
</div>
<div data-productid="2" class="product-box">
Product 2
</div>
$('.product-box').each(function(index, element) {
$.get("/GetProductInfo/", {
id: $(element).data('productid')
}, function(data) {
$(element).html(data);
});
});