开发者

Accessing list properties in the typed view from a Viewmodel

I have a master view model, with the following two lists that are from two different DB tables,

public IEnumerable <Customer> SomeCustomer { get; set; }
public IEnumerable <CustomerSite> CustomerSites { get; set; }

In my controller I have

public ViewResult Index()
{
    masterViewModel sitesModel = new masterViewModel();
    return View(sitesModel);
}

Then in my view I write

@model IEnumerable<trsDatabase.Models.masterViewModel>

If I try to access the model by using a for each statement

@foreach (var customer in Model)

When I type @customer. It will only let me access the two lists not the individual properties in the list.

I thought I would have been able to do this with e.g.

@customer.CustomerSites.UnitNo

But the furthest i can go is

@customer.CustomerSites

And this obviously will not let me access the individual properties in the lists

开发者_如何学Python

Does anyone have any ideas on what I'm doing wrong here? Do I need to define the properties from the viewmodel in the controller? (I think not)

Update

I have the following code in my viewmodel,

namespace trsDatabase.Models
{
    public class masterViewModel
    {
    public IEnumerable <Customer> Customers { get; set; }
    public IEnumerable <CustomerSite> CustomerSites { get; set; }
    }
}

Then the following in the controller,

public ViewResult Index()
{
    masterViewModel sitesModel = new masterViewModel();
    return View(sitesModel);
}

Then I changed my view declaration to

@model trsDatabase.Models.masterViewModel

This allows me to access the properties from the view perfectly, but it throws an error with the foreach loop as it can't be used when the view is inheriting the model rather than the Ienumerable list, do I need to change the syntax for rendering the list in the view and use something other than a foreachloop?


I think you need another loop, as CustomerSites is a collection:

@foreach (var customer in Model)
    foreach (var site in customer.CustomerSites)
        @site.UnitNo

EDIT AFTER COMMENT

Create a ViewModel class:

class ViewModel
{
    public IEnumerable<Customer> Customer { get; set; }
}

Populate it in the controller and pass it to View() function. Change the view to be typed (@model ViewModel). Then inside view your Model property will be of type ViewModel and you can access customers collection through @Model.Customers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜