Returning a list to strongly typed view using viewbag

孤街浪徒 提交于 2019-12-09 07:35:25

I think you can make this a bit better. First - create a new class called a ViewModel. Add this to your models folder, call it for ex. CustomerSitesViewModel.cs

In it, add a definition for

public IEnumerable Customers {get;set;}
public IEnumerable CustomerSites {get;set;}

Or you can create a ViewModel CustomerSiteViewModel.cs which contains

public Customer CustomerDetails {get;set;}
public CustomerSite CustomerSiteDetails {get;set;}

You could name the fields Customer and CustomerSite but I didn't do that for demo purposes so you don't get stuck in a recursive loop not realizing which one to call.

Then your view (to view one) is

@model CustomerViewViewModel

or if you need a list

@model IEnumerable

This is the preferred way as opposed to ViewBag data. It's strongly typed. easier to follow, and less error prone.

q is not a customer, but a sequence of customers. Therefore, when you say ViewBag.customer = q;, the ViewBag.customer property becomes of type IEnumerable<Customer>, which, quite naturally, does not have a CustomerName property.

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