【发布时间】:2016-10-11 14:33:56
【问题描述】:
我正在从 Pro ASP.NET 4.0 一书中学习 ASP.NET,但我一直坚持添加 CartController 和 Views/Cart/Index.cshtml
我添加了这样的内容:
public class CartController : Controller
{
private IProductRepository repository;
public CartController(IProductRepository repo)
{
repository = repo;
}
public ViewResult Index(string returnUrl)
{
return View("Index", "~/Views/Shared/_Layout.cshtml", new CartIndexViewModel
{
Cart = GetCart(),
ReturnUrl = returnUrl
});
}
public RedirectToRouteResult AddToCart(int productId, string returnUrl)
{
Product product = repository.Products
.FirstOrDefault(p => p.ProductID == productId);
if (product != null)
{
GetCart().AddItem(product, 1);
}
return RedirectToAction("Index", new { returnUrl });
}
private Cart GetCart()
{
Cart cart = (Cart)Session["Cart"];
if (cart == null)
{
cart = new Cart();
Session["Cart"] = cart;
}
return cart;
}
}
}
然后我已经添加到我的购物车->索引操作视图(右键单击->添加视图),如下所示:
@model SportsStore.WebUI.Models.CartIndexViewModel
@{
ViewBag.Title = "Sklep sportowy: Twój koszyk";
}
<h2>Twój koszyk</h2>
<table width="90%" align="center">
<thead>
<tr>
<th align="center">Ilość</th>
<th align="left">Produkt</th>
<th align="right">Cena</th>
<th align="right">Wartość</th>
</tr>
</thead>
<tbody>
@foreach(var line in Model.Cart.Lines) {
<tr>
<td align="center">@line.Quantity</td>
<td align="left">@line.Product.Name</td>
<td align="right">@line.Product.Price.ToString("c")</td>
<td align="right">@((line.Quantity * line.Product.Price).ToString("c"))</td>
</tr>
}
</tbody>
<tfoot>
<tr>
<td colspan="3" align="right">Razem:</td>
<td align="right">
@Model.Cart.ComputeTotalValue().ToString("c")
</td>
</tr>
</tfoot>
</table>
<p align="center" class="actionButtons">
<a href="@Model.ReturnUrl">Kontynuuj zakupy</a>
</p>
在页面上的产品摘要中,我有一个将产品添加到购物车的按钮,然后重定向到此 localhost:port/Cart/Index 页面。这是这个导航按钮:
@model SportsStore.Domain.Entities.Product
<div class="item">
<h3>@Model.Name</h3>
@Model.Description
@using(Html.BeginForm("AddToCart", "Cart")) {
@Html.HiddenFor(x => x.ProductID)
@Html.Hidden("returnUrl", Request.Url.PathAndQuery)
<input type="submit" value="+ Dodaj do koszyka" />
}
<h4>@Model.Price.ToString("c")</h4>
</div>
问题是购物车运行良好,但它的视图没有嵌入主布局/Shared/_Layout.cshtml。它只是作为单独的页面出现,不包含任何 html 标题或正文内容,只是网站的内容部分。
我发现的同一个示例的 github 项目的完成方式与 Visual Studio 主项目完全相同。 https://github.com/akatakritos/SportsStore
我检查了图书代码列表,但找不到任何错误。为什么它没有正确显示为主要布局的一部分?但在单独的视图中!
感谢任何帮助。
编辑:
我有 Views/Shared/_ViewStart.cshtml
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
【问题讨论】:
-
是不是忘记在_ViewStart.cshtml中设置Layout了?像这样的东西 @{ Layout = "_Layout"; }
标签: c# asp.net asp.net-mvc-4 razor