I am passing two list variables in an ActionResult as Below.
public ActionResult Index()
{
List<category> cat = _business.ViewAllcat().ToList();
List<Books> book = _business.ViewAllBooks().ToList();
return View(book);
}
When I run the Code I get the below error
The model item passed into the dictionary is of type System.Collections.Generic.List1[Durgesh_Bhai.Models.category], but this dictionary requires a model item of type System.Collections.Generic.IEnumerable1[Durgesh_Bhai.Models.Books].
When I am using only one List in Actionresult its working fine.
I am also new to mvc but the solution i got was to create a class which will hold all you required objects as data members and pass the object of that class.
I created a class called data and assigned all my objects to the object of this class and sent that object to model.
or you can use view bag
Class Data
{
public List<category> cat {get;set;}
public List<Books> book {get;set;}
public Data()
{
this.cat = new List<category>();
this.book = new List<Books>();
}
}
public ActionResult Index()
{
Data d=new Data();
d.cat = _business.ViewAllcat().ToList();
d.book = _business.ViewAllBooks().ToList();
return View(d);
}
Please create a new ViewModel class and store your two lists like so:
public class MyViewModel
{
public List<Category> Categories { get; set; }
public List<Book> Books { get; set; }
public MyViewModel()
{
this.Categories = new List<Category>();
this.Books = new List<Book>();
}
}
public ActionResult Index()
{
MyViewModel model = new MyViewModel();
model.Categories = _business.ViewAllcat().ToList();
model.Books = _business.ViewAllBooks().ToList();
return View(model);
}
Then in your View (index.cshtml), declare MyViewModel like so:
@model WebApp.Models.MyViewModel
<div>
your html
</div>
The concept we just used is called View Model. Please read more about it here: Understanding ViewModel
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With