如何在asp.net中将数据库内容加载到ajax?

时间:2016-10-19 05:06:48

标签: asp.net ajax

我正在使用asp.net C#尝试从数据库加载价格列到ajax文件。可能吗?还有其他方法吗?

function addProduct() {
    //this is just a product placeholder
    //you should insert an item with the selected product info
    //replace productId, productName, price and url with your real product info


    productId = productId + 1;
    var productAdded = $('<li class="product"><div class="product-image"><a href="#0"><img src="img/product-preview.png" alt="placeholder"></a></div><div class="product-details"><h3><a href="#0">Product Name</a></h3><span class="price">$25.99</span><div class="actions"><a href="#0" class="delete-item">Delete</a><div class="quantity"><label for="cd-product-'+ productId +'">Qty</label><span class="select"><select id="cd-product-'+ productId +'" name="quantity"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select></span></div></div></div></li>');
    cartList.prepend(productAdded);
}

1 个答案:

答案 0 :(得分:0)

如果你想在Ajax中加载它,你应该有一个后端服务来服务你的请求,假设它存在且它的URL是/ Product / GetProductInfo,那么你的代码应该是这样的:

function addProduct(productId) {
    //this is just a product placeholder
    //you should insert an item with the selected product info
    //replace productId, productName, price and url with your real product info

   $.ajax('/Product/GetProductInfo?productId='+productId,function(data){

    var productAdded = $('<li class="product"><div class="product-image"><a href="#0"><img src="'+data.productImageUrl+'" alt="placeholder"></a></div><div class="product-details"><h3><a href="#0">'+data.productName+'/a></h3><span class="price">$'+data.price+'</span><div class="actions"><a href="#0" class="delete-item">Delete</a><div class="quantity"><label for="cd-product-'+ productId +'">Qty</label><span class="select"><select id="cd-product-'+ productId +'" name="quantity"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select></span></div></div></div></li>');
    cartList.prepend(productAdded);
});
}

在你的按钮中,它应该调用addProduct传递产品ID,例如:

<button onclick='addProduct(4)'>Add to Cart</button>

您的后端应接受查询字符串参数productId并返回包含产品名称,价格,图片等产品信息的对象。