c# - 在 ASP.NET MVC View 中访问模型的属性

标签 c# asp.net-mvc razor

我在访问我传递 View 的模型的属性之一时遇到问题。

模型定义如下:

public class ProductBasket
{
    public ProductBasket()
    {
        Products = new List<ProductConfiguration>();
        Errors = new List<string>();
    }
    public List<ProductConfiguration> Products { get; set; }
    public List<string> Errors { get; set; }
}

在我看来,模型指令是这样声明的:

@model MyApp.ViewModels.Product.ProductBasket

我无法在 foreach 循环中访问 Products 属性。在 VisualStudio 中,当我将鼠标悬停在循环中的 Model 变量时,它显示:

List<MyApp.ViewModels.Product.ProductConfiguration> 
WebViewPage<List<MyApp.ViewModels.Product.ProductConfiguration>>.Model { get; }

这是我使用的之前模型 - 我不知道为什么会出现这个?

我做了什么

直觉告诉我,我应该能够使用 Model.Products 访问 Products 属性(请告诉我这是否不正确),但我不明白为什么 View 没有被传递ProductBasket

最佳答案

看起来您正在将 ProductConfiguration 类对象的集合传递给 View 。确保您从操作方法将 ProductBasket 类的单个对象发送到您的 View

public ActionResult Something()
{
  var vm = new ProductBasket();

 //The below line is hard coded for demo. You may replace with actual list from db.
  vm.Products.Add(new ProductConfiguration { Id=1,Name="test"});

  return View(vm);
}

假设您的 ProductConfiguration 类具有 Id 和 Name 属性。

您的 View 应该绑定(bind)到ProductBasket

@model YourNameSpaceHere.ProductBasket
<h1>Products</h1>

@foreach(var product in Model.Products)
{
  <h2>@product.Name</h2>
}

关于c# - 在 ASP.NET MVC View 中访问模型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31629247/

相关文章:

c# - VB.NET 与 C# 整数除法

c# - 对于 R# 对精度损失的提示,这是一个很好的解决方案吗?

javascript - 在 MVC .cshtml 页面中使用 JavaScript if else

c# - MVC Razor 柱模型为空

c# - 如果多个用户访问同一页面,Query String 值会改变吗?

c# - 这是在 C# 中创建线程安全类的好设计吗?

asp.net-mvc - 始终使用 WebDeploy on Destination 删除 Angular dist 文件夹内容

javascript - 保存到 View 中的多个隐藏字段

asp.net-mvc - 具有延迟加载问题的工作单元方法、nHibernate、ASP.NET MVC、CaSTLe Windsor

javascript - 简单的 AngularJS 1.5.9 组件不在 MVC 5 中呈现