问题
I am having problems accessing one of the properties of the model I am passing a View.
The model is defined like this:
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
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?
What I have done
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
?
回答1:
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);
}
Assuming your ProductConfiguration
class has an Id and Name property.
And your view should be bound to ProductBasket
@model YourNameSpaceHere.ProductBasket
<h1>Products</h1>
@foreach(var product in Model.Products)
{
<h2>@product.Name</h2>
}
来源:https://stackoverflow.com/questions/31629247/accessing-the-property-of-a-model-in-asp-net-mvc-view