How to do Lists in a view model? + dataannotations - c#

I am using asp.net mvc 3, data annotations and auto mapper.
I want to have all my annotations on properties in my view model once the properties pass validation I use auto mapper to map it back to my domain object.
I have a viewmodel that has properties that I want to have a collection of since I want to generate a table from them. I also want to use them later to use as a form to add rows to this table.
So what do I do? How do I take these properties and make a collection of them?
public class UserViewModel()
{
[Required()]
public string UserName = {get; set;}
[Required()]
public string FirstName = {get; set;}
[Required()]
public string LastName = {get; set;}
}
I want to use these properties to generate my table and be used for a form.
The only thing I can think of is doing this
public class AddUserViewModel()
{
[Required()]
public string UserName = {get; set;}
[Required()]
public string FirstName = {get; set;}
[Required()]
public string LastName = {get; set;}
}
public class UserViewModel()
{
public List<User> Users {get; set;}
public AddUserViewModel {get; set;}
public UserViewModel()
{
Users = new List<Users>();
}
}
So basically I have it as a separate view model that is enclosed into another viewmodel that contains a list of Users(my domain model)
That way I use my domain model to generate the table and my AddUserViewModel for my adding of users.
Seems kinda redundant so I am not sure if there is a better way.
Edit
I have something like this
var viewModel = new UserViewModel();
List<Users> users= UserService.GetAllUsers();
viewModel = Mapper.Map<Users, UserViewModel>(users);
return View("Index", viewModel);
I also tried
var viewModel = new UserViewModel();
List<Users> users= UserService.GetAllUsers();
viewModel.AddUserViewModel = Mapper.Map<Users, AddUserViewModel>(users);
return View("Index", viewModel);
Edit 2
I have this and it compiles but I get this error
SomeViewModel viewModel = new SomeViewModel ();
List<User> users= userService.GetAllUsers();
viewModel.UserViewModel = Mapper.Map<List<User>, List<UserViewModel>>(users);
return View("Index", viewModel);
Trying to map Domain.User to ViewModels.UserViewModel.
Missing type map configuration or unsupported mapping.
Exception of type 'AutoMapper.AutoMapperMappingException' was thrown.

Why would you want to return a list of domain objects in your view model? That's not what view models are supposed to be. View models should reference only other view models. So you have a nice UserViewModel which represents a user. Now you need to work with multiple users in your view, so either you pass an IEnumerable<UserViewModel> or if you need some other properties you design a view model for this:
public class UserViewModel
{
[Required]
public string UserName = { get; set; }
[Required]
public string FirstName = { get; set; }
[Required]
public string LastName = { get; set; }
}
public class SomeViewModel
{
public List<UserViewModel> Users { get; set; }
public string SomeOtherProperty { get; set; }
}
and now your controller action might look like this:
public ActionResult Foo()
{
SomeModel model = _repository.GetModel();
SomeViewModel viewModel = Mapper.Map<SomeModel, SomeViewModel>(model);
return View(viewModel);
}
Now inside your view you could simply use a display template for this Users property (Html.DisplayFor(x => x.Users)) to show a list of them.
UPDATE:
After seeing your update here's how to proceed in terms of good practices:
public ActionResult Foo()
{
IEnumerable<Users> users = _repository.GetUsers();
IEnumerable<UserViewModel> usersViewModel = Mapper
.Map<IEnumerable<Users>, IEnumerable<UserViewModel>>(users);
return View(usersViewModel);
}
I've also used an AutoMap attribute in a sample project which could simplify your code to this:
[AutoMap(typeof(IEnumerable<Users>), typeof(IEnumerable<UserViewModel>))]
public ActionResult Foo()
{
IEnumerable<Users> users = _repository.GetUsers();
return View(users);
}
This attribute will automatically run after the controller action and before the view is rendered and would use AutoMapper to replace the model with the corresponding view model.

Related

How to have a view model which contains two models

In a view i need a view model which contains two models. I dont know how to retrieve data in the repository.
There is a Products model which has a foreign key to another model.
Here is my PRODUCTS model:
public class Products
{
public int ProductId {get; set;}
public string Productname {get; set;}
public int ProductTypeID { get; set; }
[ForeignKey("ProductTypeID")]
public virtual ProductTypes ProductTypes { get; set; }
}
And this is my PRODUCTTYPE model:
public class ProductTypes
{
public int ProductTypeId {get; set;}
public int ProductTypeName {get; set;}
}
Now I want to use them in a View, so I made a viewmodel
public class ProductsViewModel
{
public Products Products { get; set; }
public IEnumerable<ProductTypes> ProductTypes { get; set; }
}
Here is my problem. I don't know how to retrieve data from a viewmodel in a repository like this:
public async Task<IEnumerable< XXX >> GetAllProducts()
{
return await _RepositoryContext.Set<xxx>.ToListAsync();
}
Finally this is my Controller:
public async Task<IActionResult> index()
{
return View(await ProductRepository.GetAllProducts());
}
In your repository you use include expression like this
public async Task<IEnumerable< Products >> GetAllProducts()
{
var products = _RepositoryContext.Set<Products> ();
return await products.include(x =>x.ProductType).ToListAsync();
}
But I think you need to modify your models. you are returning domain classes in controller as view Model which is not a good idea, you should have separate model classes and should use Automapper to map domain to model classes so that on client side you send only model classes which may have many extra columns than domain classes . Here is how your model classes should look like
public class Products
{
public int ProductId {get; set;}
public string Productname {get; set;}
public int ProductTypeID { get; set; }
[ForeignKey("ProductTypeID")]
public virtual ProductTypes ProductTypes { get; set; }
}
public class ProductTypes
{
public int ProductTypeId {get; set;}
public int ProductTypeName {get; set;}
}
Now models should be like this
public class ProductsModel
{
public int ProductId {get; set;}
public string Productname {get; set;}
public int ProductTypeID { get; set; }
public virtual ProductTypesModel ProductTypes { get; set; }
public string ProductTypeName {get; set;}
}
public class ProductTypesModel
{
public int ProductTypeId {get; set;}
public int ProductTypeName {get; set;}
}
Now repository method should look like this
public async Task<IEnumerable< Products >> GetAllProducts()
{
var products = _RepositoryContext.Set<Products> ();
return await products.include(x =>x.ProductType).ToListAsync();
}
Finally this would be your controller Controller,
public async Task<IActionResult> index()
{
var productList= await ProductRepository.GetAllProducts()
var ProductModels = Mapper.Map<IEnumerable<Products>, IEnumerable<ProductsModel>>( productList)
return View(ProductModels);
}
To Know how to setup AutoMapper please refer to my this post, How to setup Automapper in ASP.NET Core
It all depends on your architecture. However, Repository might not be the best place to do the mapping between models and viewmodels because once the ORM is changed the repository will possibly be modified too while this mapping could be somewhere to avoid unnecessary changes. I personally prefer to do the mapping either in BLL or in viewmodel itself without using AutoMapper. Here is one possible way of mapping in viewmodels:
public class ProductsDto
{
public int ProductId { get; set; }
public string Productname { get; set; }
public virtual ProductTypeDto ProductTypes { get; set; }
public void SetDto(Products obj)
{
if (obj == null)
return;
this.ProductId = obj.ProductId;
this.Productname = obj.Productname;
if (obj.ProductTypes != null)
{
this.ProductTypes = new ProductTypeDto();
this.ProductTypes.SetDto(obj.City);
}
}
}
public class ProductTypeDto
{
public int ProductTypeId { get; set; }
public int ProductTypeName { get; set; }
public void SetDto(ProductType obj)
{
if (obj == null)
return;
this.ProductTypeId = obj.ProductTypeId;
this.ProductTypeName = obj.ProductTypeName;
}
}
Using viewmodels:
public ProductsDto GetProductsDto(Products obj)
{
var dto = new ProductsDto();
dto.SetDto(obj);
return dto;
}
----------------------------------------------------------
var products = _RepositoryContext.Products.ToList();
var productsDto = products?.Select(GetProductsDto);
It depends on what you actually want to do within your view: A view model is supposed to contain exactly the data necessary to display the view. Usually, you would not want to include more data there. So using database models inside of a view model is not the best choice; it would be better to design actual view models that match the stuff you display, and then you decide how to properly get that data.
From how your view model looks, I could assume two use cases:
You want to display a set of products, and list those product types that that set of products have.
You want to display a set of products, and a list of all product types.
Option 2 is really simple and requires you to only query each entity type once:
var viewModel = new ProductsViewModel
{
Products = await db.Products.ToListAsync(),
ProductTypes = await db.ProductTypes.ToListAsync(),
};
Option 1 can be solved naively by including the product types through the navigation property in the Product entity:
var products = await db.Products.Include(p => p.ProductType).ToListAsync();
var viewModel = new ProductsViewModel
{
Products = products,
ProductTypes = products.Select(p => p.ProductType).Distinct().ToList(),
};
This however has the downside that with few distinct product types you will be loading each product type multiple times. Because your product type has only an id and a name, this is not that problematic but for more complex types it can be.
A different approach would be to query the product type ids first from the list of products, and then loading the product types afterwards:
var products = await db.Products.Include(p => p.ProductType).ToListAsync();
var productTypeIds = product.Select(p => p.ProductTypeId).Distinct().ToList();
var viewModel = new ProductsViewModel
{
Products = products,
ProductTypes = await db.ProductTypes.Select(t => productTypeIds.Contains(t.Id)).ToListAsync(),
};
Two notes:
I ignored the existence of your repository here and just assumed that you are using an EntityFramework DbContext here. If you want to abstract that into a repository, you can do so.
The entity is named Products but only contains information about a single product. Similarly, the view model contains a property Products of that exact same type. That does not make a lot of sense to me, so I just assumed that the entity is called Product and represents a single item, while the ProductsViewModel has Products, a list of Product.

MVC Two controllers One View

I am trying to have a details view in an existing controller that joins two controllers and passes into the view, but everything i have tried so far has not worked. I have 4 data models and what i would like is to use 2 of them Company and Staff. So when i select details on a specific Company it will return all Staff associated to that Company in the same view.
HRDataModel class
public partial class HRDataModel : DbContext
{
public HRDataModel()
: base("name=HRDataModel")
{
}
public virtual DbSet<Company> Companies{ get; set; }
public virtual DbSet<Attribs> Attribs{ get; set; }
public virtual DbSet<Staff> Staffs { get; set; }
....
Company Data Model
[Table("Company")]
public partial class Company
{
public Company()
{
Staffs = new HashSet<Staff>();
}
public virtual ICollection<Staff> Staffs { get; set; }
public int companyId{ get; set; }
[Required]
[StringLength(10)]
public string companyName{ get; set; }
.....
Staff Data Model
public partial class Staff
{
public Staff()
{
Skills = new HashSet<Skill>();
}
public virtual Company Company{ get; set; }
public virtual ICollection<Skill> Skills { get; set; }
public int staffId { get; set; }
.........
And i am trying to get my Details method in CompanyController to show details of all active Companies in the db and also all Staff attached to that Company
[Route("Company/Staff/1}")]
public ActionResult Details(int id)
{
Company co = db.Companies.Find(id);
...How to implement????
return View(bu);
}
If anyone can point me in the right direction that would be great. I have tried and tried but cannot get anything to work?
Since Company includes Staff you can use the include method to include related entities.
var company = db.Companies.Include(c => c.Staffs).FirstOrDefault(x => x.id == companyId);
return View(company);
And in your view:
#foreach(var staff in Model.Staffs) { ... }
You need to pass a data structure which has the company info and staff details to your view. You may pass your existing Comapny entity class to do this. But the problem is, It makes your razor view tightly coupled to your Entity which was generated by the ORM. What if you switch your Data access layer to something else tomorrow. So this solution is not great.
So you should use a view model ( A simple POCO class) which has properties which you need to render in the view. Then read your entity from db in your action method, map it to a vie wmodel instance and send it.
Create a view model like this.
public class CompanyInfo
{
public int Id {set;get;}
public string Name {set;get;}
public List<StaffItem> Staffs {set;get;}
public CompanyInfo()
{
this.Staffs = new List<StaffItem>();
}
}
public class StaffItem
{
public int Id {set;get;}
public string Name {set;get;}
}
In your action method read the Company entity and map it to the view model
public ActionResult Details(int id)
{
var vm = new ComapnyInfo();
var company = db.Companies
.Include(r => c.Staffs)
.FirstOrDefault(x => x.companyId==id);
if(co!=null)
{
//Map the property values now
vm.Name = co.companyName;
vm.Id = co.companyId;
if(co.Staffs!=null)
{
vm.Staffs = co.Staffs.Select(f=> new StaffItem {
Id=f.staffId,
Name = f.staffName}).ToList();
}
}
return View(vm);
}
Now your view should be bound to the CompanyInfo view model
#model YourNamespace.CompanyInfo
<h2>#Model.Name</h2>
<h3>Staffs</h3>
#foreach(var staff in ModelStaffs)
{
<p>#staff.Name</p>
}
If you do not like the manual mapping, You may consider using a mapping libarary like Automapper.
Hi #stackface you dont pass two controllers to get both views for that what you do is create one View Model which is essentially a container for multiple models and pass that into the view from the controller.
E.g. Model 1, Model2, ModelN all are needed so you have a class and in that class it has properties consisting of Model1, Model2 and Model3 so that way you pass in your class which has all the needed models.
E.g.
public class Company{...}
public class Staff{...}
public class ViewModel{
public Company Company {get;set;}
public List<Staff> Staff{get;set;}
}
controller:
{
var viewModel = new ViewModel();
viewModel.Company = db.Companies.FirstOrDefault(x => x.id == companyId);
viewModel.Staff = db.Staff.Where(x => x.CompanyId == campanyId).ToList() //or whatever your properties are called.
Return View(viewModel);
}
Update your view to take type ViewModel.
You can also compose a view by calling controller actions that return partial views.
The advantage is that you can reuse the partial views and their actions, e.g. to show the company details with the same layout on different pages. This increases consistency and maintainability.
The drawback is that you loose flexibility: if a certain page requires a different layout, you should create a new view. Performance might also be lower because you hit the backend with many small operations instead of a single big one.
The combined viewmodel to show both company and staff details only needs to know how to access the required data:
public class CompanyAndStaffDetailsViewModel {
public long CompanyId { get; set; }
public long StaffId { get; set; }
}
The following action renders the combined view:
public ActionResult Details(long companyId, long staffId) {
var viewModel = new CompanyAndStaffDetailsViewModel {
CompanyId = companyId,
StaffId = staffId
};
return View("Details", viewModel);
}
The "Details" View composes the usecase by calling actions to render partial views:
#model CompanyAndStaffDetailsViewModel
#Html.Action("CompanyInfoPartial", "Company", new { companyId = Model.CompanyId })
#Html.Action("StaffInfoPartial", "Staff", new { staffId = Model.StaffId })
The "Company" controller provides a reusable action to render company details:
public ActionResult CompanyInfoPartial(long companyId) {
Company co = db.Companies.Find(companyId);
var model = Mapper.Map<CompanyViewModel>(co); // map persistable entity to ViewModel
return PartialView("_CompanyInfoPartial", model);
}
Then the parital View _CompanyInfoParital.cshtml only has to deal with the Company Info stored in the CompanyViewModel and knows nothing about Staff:
#model CompanyViewModel
#Html.DisplayFor(m => m.CompanyName)
// etc ...
The idea for the StaffInfoPartial action is the same as for CompanyInfoPartial.

View using DTO - ASP.NET MVC

I'm fairly new to MVC and I've been trying to create a view using a DTO as the Model Class, but it seems to be using the Data Context class I use for my Models, even though I am clearing the selection when I am creating the view.
This issue seems to be causing a NullReferenceException which is caused by the following exception being thrown and the view not having any returned to it.
ITSSkillsDatabase.Models.PersonSkillSetsDTO: : EntityType 'PersonSkillSetsDTO' has no key defined. Define the key for this EntityType.
PersonSkillSets: EntityType: EntitySet 'PersonSkillSets' is based on type 'PersonSkillSetsDTO' that has no keys defined.
My DTO:
namespace ITSSkillsDatabase.Models
{
public class PersonSkillSetsDTO
{
public int IDSkillset { get; set; }
public int IDCategory { get; set; }
public string Product { get; set; }
public string P_Version { get; set; }
public string Notes { get; set; }
public int PersonSkillsID { get; set; }
public int IDPerson { get; set; }
public int Score { get; set; }
public DateTime ScoreDate { get; set; }
public int TargetScore { get; set; }
public DateTime TargetDate { get; set; }
public DateTime RefresherDate { get; set; }
}
}
Controller method:
public ActionResult SkillSets(int? id)
{
try
{
if (id == null)
{
return HttpNotFound();
}
var viewModel = (from a in db.SkillSets
join c in db.PersonSkills on a.IDSkillset equals c.IDSkillSet
where c.IDPerson == id
select new Models.PersonSkillSetsDTO
{
IDSkillset = a.IDSkillset,
IDCategory = a.IDCategory,
Product = a.Product,
P_Version = a.P_Version,
Notes = a.Notes,
PersonSkillsID = c.PersonSkillsID,
IDPerson = c.IDPerson,
Score = c.Score,
ScoreDate = c.ScoreDate,
TargetScore = c.TargetScore,
TargetDate = c.TargetDate,
RefresherDate = c.RefresherDate
}).ToList();
return View(viewModel);
}
catch
{
return View(); //this is where the NullReferenceException is thrown
}
}
These are the settings when I'm creating the view:
I realise I can get rid of the NullReferenceException by checking for null values, but I don't have any idea how to fix the issue with my DTO.
I am going to try to explain using a ViewModel/DTO to create a Form and POST back.
ViewModels are outside of the Database Context, So if you are using a ViewModel you have to Map your data from ViewModel to Model and Model to ViewModel.
So if you are reading from Database
Create DBContext
read data you want to read
Map to a ViewModel
Pass ViewModel to the View or API
If you are writing to the database
POST ViewMdoel from View to Controller (You can use Ajax)
Create DBContext
Map from ViewModel to Model
Save Model to Database
let's say you have a DTO,
public class CountryDTO
{
public int CountryId { get; set; }
[Display(Name = "Country Name")]
[Required(ErrorMessage = "This field is required")]
public string CountryName { get; set; }
[Display(Name = "Latitude")]
[Required(ErrorMessage = "This field is required")]
public double CentralLat { get; set; }
[Display(Name = "Longitude")]
[Required(ErrorMessage = "This field is required")]
public double CentralLang { get; set; }
[Display(Name = "GMT Offset")]
[Required(ErrorMessage = "This field is required")]
public double GMTOffSet { get; set; }
[Display(Name = "Currency")]
[Required(ErrorMessage = "This field is required")]
public string Currency { get; set; }
}
Create a controller i.e. CountryController and you have a Views Folder Country, Right Click Country Folder Add --> View, Name it CreateCountry and Select Model to be CountryDTO
You can't select DataContext here , because DTO is not part of the Context
This will create your view with Fields from the DTO.
Now in your Controller you need 2 Actions
GET method to return the View
POST method to POST back the form
public ActionResult CreateCountry()
{
return PartialView(new CountryDTO());
}
Now in the POST method you will Pass the DTO, Let's assume you have a Country table in your Database, you will have to create a New Country type Object and add to the Context
[HttpPost]
public ActionResult CreateCountry(CountryDTO model)
{
if (ModelState.IsValid)
{
// Model State is Valid
// here you will create Context
using (var dbContext = new DATBASE_CONTEXT())
{
var newCountry = new Country() // Country is a Model from Database
{
CountryName = model.CountryName,
CentralLat = model.CentralLat,
// Map All Properties from View Model to Model
};
// Add the New Country to the Countries
dbContext.Countries.Add(newCountry);
// Save Database Changes
dbContext.SaveChanges();
}
}
return PartialView(model);
}
IF you want to display this Country:
public ActionResult CountryDetails(int id)
{
var model = new CountryDTO();
using (var dbContext = new DATABASE_CONTEXT())
{
var country = dbContext.Country.First(s => s.CountryId == id);
model.CountryName = country.CountryName;
// Same for other Properties
// You can use AutoMapper Library to Map from Model to DTO/ViewModel
}
return View(model);
}
try
{
// <...>
return View(viewModel);
}
catch
{
return View(); //this is where the NullReferenceException is thrown
}
You get NullReferenceException because your view expects the model and doesn't perform null checks in Razor.
To verify this, you can create a dummy model and pass it into your return View(/* model */); call.
As I understood the exception trouble is not with DbContext but with lame model: "No key defined". I think checking data-annotations might help.
I created a new View Model which contains everything I need from the two models.
I then set the values for the View Model within the controller.
Which gave me the result I wanted.

MVC Entity Framework DropDownListFor<>

I would like to follow best MVC best practise for creating DropLists.
I have 3 Models (I have cut them down for the purposes of this)
Model One
Student
public int ID {get;set;}
public string Name {get;set}
public Site SiteID {get;set;}
Model Two
Site
public int ID {get;set;}
public string SiteName {get;set}
Model Three
VM
public int ID {get;set}
public student Students {get;set;}
public DateTime Date { get { return DateTime.Now; } }
public bool Criteria {get;set;}
In my VM view I am using EditorFor html helpers to populate my VM and Student Models. The site model is pre populated at the database seed.
I am looking for the best way to include a dropdownlist of sites on my VM view, that will map to my student model.
How to I correctly set up my models to achieve this?
In short, you want the DropDownListFor extension method and to put a List<Site> into the view model.
Here is a Fiddle that demonstrates your case. The Fiddle has more details. The nuts and bolts are here:
ViewModel - Add a List<Site>
public class MyViewModel
{
public MyViewModel()
{
this.Sites = new List<Site>();
}
public int ID { get; set;}
public Student Students { get; set; }
public DateTime Date { get { return DateTime.Now; } }
public bool Criteria { get; set; }
public List<Site> Sites { get; set; }
}
View - Use DropDownListFor
#Html.DropDownListFor(m => m.Sites,
new SelectList(Model.Sites, "ID", "SiteName"))
In psuedo-code, the above says
The Sites object in the model contains the properties to display.
Create a new SelectList using the Sites object in the model. Use the ID property as the data value and the SiteName property as the data text.
Create a drop down list based on the above info.
Controller
This just passes a seeded view model to the view.
public ActionResult Index()
{
var vm = SeedFromDatabase();
return View(vm);
}
private MyViewModel SeedFromDatabase()
{
var vm = new MyViewModel();
vm.Sites.Add(new Site(0, "one"));
vm.Sites.Add(new Site(1, "two"));
vm.Sites.Add(new Site(2, "three"));
return vm;
}
ViewModel
public class VM
{
public int ID {get;set}
public student Students {get;set;}
public SelectList SiteList {get;set;}
public int SiteID {get;set;}
public DateTime Date { get { return DateTime.Now; } }
public bool Criteria {get;set;}
}
Load View Action
public ActionResult LoadVMView(){
var model = new VM();
var items = GetSitesFromDatabase().Select(s => new SelectListItem(){
Text = s.SiteName,
Value = s.ID.ToString()
});
model.SiteList = new SelectList(items);
return View(model);
}
View:
#Html.DropDownListFor(m => m.SiteID, Model.SiteList)
On Post
[HttpPost]
public ActionResult LoadVMView(VM model){
var selecteSiteID = model.SiteID;
}

Create View With One-Many Relationship

I have 2 simple models:
public class Country
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Region> Region { get; set; }
}
public partial class Region
{
public int ID { get; set; }
public string Name { get; set; }
public int CountryID { get; set; }
public virtual Country Country { get; set; }
}
Is it possible to have a single page to handle the creation of a country whereby the user inputs the country with multiple regions and then only posts to the server?
I've seen an implementation here where you create a custom ViewModel with numbered properties (Region1, Region2, Region3, etc) but it's limiting, any suggestions?
(I know AngularJS can be used to do this however I have no experience in this space as of yet.)
Thanks
Yes its very possible it just depends on how you plan to implement this.
My favourite style of implementing One to Many pages is initially creating the "one" (country) then redirecting to a page with a grid element where users can add the many (regions) to the one. It works well and its a very easy way for both the programmer to create and the user to understand.
As for creating a country with multiple regions in a single post, it could be done but you must think of how the implementation will work.
Sure, this is easy to do. You have defined your data model. Either you use that also as your View Model, or you can create a new model that is a complex object. The methods in your type:
public virtual Country Country { get; set; }
public virtual ICollection<Region> Region { get; set; }
These method being present normally indicates you're using Entity Framework and that these are "related entities" that you can traverse via this "navigation property" at run-time. You can create a Country and populate the Region collection on the fly when you try to use it.
Here is a good example of using a View Model:
What is ViewModel in MVC?
///Example of a Controller method creating a view model to display
[HttpGet]
public ActionResult Index()
{
var user = _userService.Get(User.Identity.Name);
var customerId = GlobalDataManager.GetCustomerId();
if (_error != null)
{
ModelState.AddModelError("", _error);
_error = null;
}
var model = new InboundListModel();
model.Initialize(customerId, user.CompanyId);
foreach (var campaign in model.Campaigns)
{
model.InitializeCallProggress(campaign.Id, _callInfoService.GetCallsCount(campaign.Id));
}
return View(model);
}
This View Model can be anything you want but it does need to be one type. So if you want 2 put 2 types in the ViewModel you just need a new container object:
public class ComplexViewModel
{
public Country Country { get; set; }
public ICollection<Region> Regions { get; set; }
}
Then you just need a way to populate the data like the example above where I call Initialize. This goes out to EF via a DAL project and retrieves the data for the model.

Categories

Resources