在ASP.NET MVC视图中访问模型的属性 [英] Accessing the property of a model in ASP.NET MVC View
问题描述
我在访问通过视图的模型的属性之一时遇到问题.
I am having problems accessing one of the properties of the model I am passing a 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; }
}
在我看来,模型指令的声明如下:
In my view the model directive is declared like this:
@model MyApp.ViewModels.Product.ProductBasket
我无法在foreach
循环中访问Products
属性.在Visual Studio中,当我将Model
变量悬停在循环中时,它显示:
I am unable to access the Products
property in a foreach
loop. In VisualStudio when I hover of the Model
variable in the loop it shows:
List<MyApp.ViewModels.Product.ProductConfiguration>
WebViewPage<List<MyApp.ViewModels.Product.ProductConfiguration>>.Model { get; }
这是我以前使用的上一个模型-我不知道为什么会出现这个模型?
This is the previous model I was using - I don't know why this is there?
我做了什么
本能告诉我,我应该可以使用Model.Products
访问Products属性(请告诉我这是否不正确),但是我不明白为什么视图没有通过ProductBasket
?>
Instinct tells me I should be able to access the Products property with Model.Products
(please tell me if this is incorrect), but I don't understand why the view isn't being passed a ProductBasket
?
推荐答案
看起来您正在将ProductConfiguration
类对象的集合传递给视图.确保从操作方法向视图发送ProductBasket
类的单个对象
Looks like you are passing a collection of ProductConfiguration
class objects to the view. Make sure you are sending a single object of ProductBasket
class to your view from your action method
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属性.
Assuming your ProductConfiguration
class has an Id and Name property.
您的视图应绑定到ProductBasket
@model YourNameSpaceHere.ProductBasket
<h1>Products</h1>
@foreach(var product in Model.Products)
{
<h2>@product.Name</h2>
}
这篇关于在ASP.NET MVC视图中访问模型的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!