jquery - MVC Asynchronous Ajax Calls -
i'm working on ecommerce website , have following template:
<div class="product-box"> product 1 </div> <div class="product-box"> product 2 </div> <div class="product-box"> product 3 </div>
the website asp.net mvc, want fill different product box product information asynchronously using jquery ajax calls mvc controller, best way it?
i can think of that
<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>
but doesn't make sense , not best way it. imagine have 1000 products, madness. can advice best way can achieve this?
you can using pure asp.net mvc using renderaction
invokes specified child action method , renders result inline in parent view.
example code:
@{html.renderaction("getproductinfo", "yourcontroller", new { id: yourproductid });}
if want perform same opertaing using jquery, recommend use custom data-
prefixed attributes store product id.
here example using .each() , .data()
html
<div data-productid="1" class="product-box"> product 1 </div> <div data-productid="2" class="product-box"> product 2 </div>
script
$('.product-box').each(function(index, element) { $.get("/getproductinfo/", { id: $(element).data('productid') }, function(data) { $(element).html(data); }); });
Comments
Post a Comment