开发者

How to make a Viewmodel of type IEnumerable?

开发者 https://www.devze.com 2023-03-05 10:04 出处:网络
I am using the following code for a master view model that contains two lists of data, namespace trsDatabase.Models

I am using the following code for a master view model that contains two lists of data,

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

I am using the following code to pass the veiwmodel to the view,

public ViewResult Index()
{
    masterViewModel sitesModel = new masterViewModel();

    return View(sitesModel);
}

Then in my view I have the following,

@model IEnumerable<trsDatabase.Models.masterViewModel>

foreach (var site in customer.CustomerSites)
{
    foreach (var cust in customer.Customers)
    {
        <tr>
            <td>
                @cust.CustomerName
            </td>
            <td>
                @site.UnitNo
            </td>

using the above code I am able to access all properties from the two lists in the viewmodel, however when I navigate to the view I get an error as the view is expecting an IEnumerable. If I change the declaration to just pass the viewmodel

@model trsDatabase.Models.masterViewModel

the foreach statement won't work, it gives this error

The model item passed into the dictionary is of type 'trsDatabase.Models.masterViewModel', but this dictionary requires a model item of type 'System.Collectio开发者_开发技巧ns.Generic.IEnumerable`1[trsDatabase.Models.masterViewModel]'.

Can anyone offer any advice or point me in the right direction for resolving this, is it possible to make my viewmodel IEnumerable?


Change this

@model IEnumerable<trsDatabase.Models.masterViewModel>

to this

@model trsDatabase.Models.masterViewModel

You are passing in a single instance of masterViewModel, so your view should expect a single instance, which is exactly what the error is telling you if not in a cryptic way.


Yes You can... in you Model (masterViewModel) make the Customers and CustomerSites List like this:

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

in the same Model, define a method that would return IEnumerable like this:

public IEnumerable<Customer> Getall()
        {
            List<Customer> lcustomer= new List<Customer>();
            //Get Customer data from Database or wherever
            lcustomer.Add(new Customer{ firstname= "Quentin ", lastname= "tarantino" });
            return lcustomer;
        }

In your controller, instantiate your Model. then call Getall() method which would return IEnumerable basically a list of customers, and pass it to your View

var rep = new masterViewModel();
var model = rep.Getall();
return View(model);
0

精彩评论

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