Accessing the property of a model in ASP.NET MVC View

独自空忆成欢 提交于 2019-12-22 16:53:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!