如何将数据传递到嵌套布局
本文关键字:嵌套 布局 数据 | 更新日期: 2023-09-27 17:57:03
假设我想在我的.NET MVC 4应用程序中扩展我的布局。所以我以一种非常简单的方式创建了一个嵌套布局:
_Root.cshtml
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
</head>
<body>
@RenderBody()
</body>
_productView.cshtml
@{
Layout = "~/Layouts/_Root.cshtml";
}
_productListView.cshtml
@{
Layout = "~/Layouts/_Root.cshtml";
}
现在,我从数据库中获取了一个产品,并希望在_productView.cshtml中设置产品类别的标题。例如,假设我想要一个电子产品的标题。我想在制作视图模型并在控制器中返回视图之前从数据库中获取产品时执行此操作:
产品控制器
public ActionResult Index(string id) {
var product= repository.GetById(new Guid(id));
if(product== null) {
throw new HttpException(404, "Not Found");
}
var model = Mapper.Map<IProduct, ProductViewModel>(product);
return View(model);
}
我想做的是从产品中获取产品类型并在 _productView.cshtml 中使用它,但我知道它不能用 viewbag 完成。那么我该怎么做呢?
问候乔纳森
更新我将扩展示例:
如果我在我的控制器中这样做:
public ActionResult Index(string id) {
var product= repository.GetById(new Guid(id));
if(product== null) {
throw new HttpException(404, "Not Found");
}
Viewbag.ProductType = product.productType;
var model = Mapper.Map<IProduct, productViewModel>(product);
return View(model);
}
然后在我的产品View.cshtml中
_productView.cshtml
@{
Layout = "~/Layouts/_Root.cshtml";
}
@Viewbag.productType
我将收到一个编译错误,告诉我当前上下文中不存在视图包。
我对产品的看法如下所示:
@model producttest.product.Web.ProductViewModel
@{
Layout = "~/Layouts/_productView.cshtml";
ViewBag.Title = @Model.Name;
}
<h1>@Model.Name)</h1>
<section>
<h2>@Model.Description, @Model.Price</h2>
<p>
@Model.ImageUrl<br />
</p>
</section>
这就是我试图实现的目标,但我读到Viewbag不能这样使用,我怎么能以另一种方式做到这一点?
更新 2:
Viewbag只是一个错字,这是实际代码:
Compiler Error Message: CS0103: The name 'ViewBag' does not exist in the current context
Source Error:
Row 3:
Row 4: }
Row 5: @ViewBag.productType;
首先要注意的是,您的视图中不需要包含此内容
<body>
@RenderBody()
</body>
这仅在布局中是必需的。请记住,@RenderBody是视图标记的占位符。
我建议您强烈键入视图以使用 ViewModel,这是一种表示您希望传递给视图的数据的 POCO。有些人只是传递他们正在使用的对象,这是有效的,但有时您使用的对象和您想要在视图上表示的内容可能不同,因此拥有单独的 ViewModel 更有意义。
您可以使用它标记视图以选择所需的强类型对象。
@model MyProject.ViewModels.MyViewModel
然后,您可以直接在视图中访问属性,如下所示
@Model.MyProperty
我想通了!由于我使用了嵌套布局结构,因此我将布局从 View 文件夹移动到名为"布局"的单独文件夹中。在每个"视图"文件夹中都有一个引用命名空间的 Web.config,由于我将布局复制到另一个文件夹,因此缺少此文件。
感谢@JMK和赫斯特@David的帮助,让我走到了这条路上!
问候乔纳森