我正在学习 asp,我只是找不到正确的方法来实现这样的功能:
页面上有几个带有数据的 div,当您单击按钮时,您需要将实际数据传输给它们(并为它们创建复杂的 html 标记)而无需重新加载页面。
示例:
该页面有一个购物车,它显示其中的商品数量、它们的总价以及下拉列表中的最后 3 件商品。购物车布局位于_Layout.cshtml。当页面加载时以及单击“添加产品”按钮时,应填写购物车(html 代码)。并且无需重新加载页面。
问题:价格、数量和列表都是不同的块(你不能只返回它们所有的公共 html ),在向它们插入数据之前,需要在页面上找到它们。我试着这样做:
- 我创建了一个单独的 js 函数,在必要时调用它,并在其中 ajax 接收数据并形成 html 。
function SmallCartUpdate() {
$.ajax({
type: "GET",
url: "Carts/SmallCart",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function(result) {
$("#SmallCartCount").text(result.count);
$("#SmallCartPrice").text(result.price);
var productList = '';
$.each(result.lastAdded, function(index, item) {
productList += '<li > <a href="#">' + item.Product.Title + '</a></li >';
})
$("#SmallCartList").html(productList);
},
});
}
但是用这种方式为列表创建html并不方便,我想做一个更复杂的结构。并且无法访问 Razor。
- 调用控制器方法并返回 PartialView 并在其中找到块并将数据插入其中。
@ {
var productList = ViewData.Eval("lastAdded") as List < ShopStore.Models.Cart > ;
}
@foreach(var item in @productList) {
<li > < a href = "#" > +@item.Product.Title + < /a></li >
}
<script type = "text/javascript" >
$("#SmallCartCount").text(ViewData.Eval("count"));
$("#SmallCartPrice").text(ViewData.Eval("price"));
</script>
这里js不起作用,此外,我不清楚如何将形成列表的foreach放入 $("#SmallCartList").text());
问题:这个功能是如何实现的?
谢谢!
局部视图:
javascript: