I'm working on an eCommerce website and I have the 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 is ASP.NET MVC, I want to fill the different product box with product information asynchronously using jQuery ajax calls to my MVC controller, what is the best way to do it?
I can already think of something like 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 this doesn't make sense and is not the best way to do it. Imagine I have 1000 products, madness. Anybody can advice the best way I can achieve this?
you can try this:
you can use data-*
attribute to provide product numbers like:
<div data-id="1" class="product-box">
<div data-id="2" class="product-box">
<div data-id="3" class="product-box">
.......
// more
$(function(){
$('.product-box').each(function(){
var dataID = $(this).data('id');
$.get("/GetProductInfo/" + dataID, {}, function (data) {
$("#product"+dataID).html(data);
});
});
});
You can do it using pure ASP.NET MVC using RenderAction
Invokes the specified child action method and renders the result inline in the parent view.
Example code:
@{Html.RenderAction("GetProductInfo", "YourController", new { id: YourProductId });}
If you want to perform same opertaing using jQuery, I would recommend you to use custom data-
prefixed attributes to store product id.
Here is an example using .each() and .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);
});
});