Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass multiple parameters to a view?

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.

like image 912
Mayank Bhuvnesh Avatar asked Jul 14 '15 07:07

Mayank Bhuvnesh


2 Answers

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);
}
like image 156
Sujit.Warrier Avatar answered Oct 12 '22 15:10

Sujit.Warrier


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

like image 21
alexan Avatar answered Oct 12 '22 14:10

alexan