【问题标题】:Accessing the property of a model in ASP.NET MVC View在 ASP.NET MVC 视图中访问模型的属性
【发布时间】:2015-07-25 17:32:19
【问题描述】:

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

模型定义如下:

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 属性(如果这不正确,请告诉我),但我不明白为什么视图没有通过 ProductBasket 传递?

【问题讨论】:

  • 检查您是否在控制器中传递了正确的模型,是的,您应该能够使用 Model.Products 访问产品。

标签: c# asp.net-mvc razor


【解决方案1】:

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

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 属性。

你的视图应该绑定到ProductBasket

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

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

【讨论】:

  • 我的错误,就像你建议的那样,我将旧模型传递给视图。令人困惑的是,我现在确保返回 ProductBasket 并构建项目,但我仍然得到相同的 List ??
  • 如果您将鼠标悬停在 Model.Products 上,您会得到它,这是正确的。
  • 我意识到我只是悬停在模型上
  • 这意味着您从您的操作方法向视图发送了错误的模型。正如我在答案中提到的,确保它是 productbasket 类的单个对象。试试我发布的代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
相关资源
最近更新 更多