如何将多个参数传递给视图?

7
我将两个列表变量传递给ActionResult,如下所示。
public ActionResult Index()
{
    List<category> cat = _business.ViewAllcat().ToList();
    List<Books> book = _business.ViewAllBooks().ToList();
    return View(book);
}

当我运行代码时,我遇到了以下错误:

传递给字典的模型项的类型是 System.Collections.Generic.List1[Durgesh_Bhai.Models.category], 但该字典需要类型为 System.Collections.Generic.IEnumerable1[Durgesh_Bhai.Models.Books] 的模型项。

当我在 ActionResult 中只使用一个列表时,它可以正常工作。


请查看此链接:http://stackoverflow.com/questions/27517239/using-multiple-models-in-a-single-controller/27518525#27518525 - Mairaj Ahmad
我认为问题出在视图上,请把你的 Index 视图贴在这里。 - HBhatia
4个回答

5
我对mvc也是新手,但我得到的解决方案是创建一个类,将所有所需对象作为数据成员保存,并传递该类的对象。我创建了一个名为"data"的类,将所有对象分配给该类的对象,并将该对象发送到模型。或者您可以使用视图包。
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);
}

4
请创建一个新的 ViewModel 类并按以下方式存储您的两个列表:
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);
}

然后,在您的视图(index.cshtml)中,像这样声明MyViewModel:

@model WebApp.Models.MyViewModel

<div>
    your html
</div>

我们刚刚使用的概念叫做视图模型。请在这里阅读更多相关信息:理解ASP.NET MVC中的视图模型


2
创建一个包含两个列表的新对象。
public ActionResult Index()
{
    List<category> cat = _business.ViewAllcat().ToList();
    List<Books> book = _business.ViewAllBooks().ToList();
    return View(new CatBooks { Cats = cat, Books = book });
}

public class CatBooks {
    public List<category> Cats { get; set; }
    public List<Books> Books { get; set; }
}

0
你应该创建一个 ViewModel 类(只是一个 .cs 类),其中包含页面上所需的所有内容。
然后在 View 的第一行,你应该使用 ViewModel 类作为你的模型。
然后在控制器操作中填充你的模型,例如:
public ActionResult Index()
    {
        List<category> cat = _business.ViewAllcat().ToList();
        List<Books> book = _business.ViewAllBooks().ToList();
        return View(new MyViewModel() { Cats = cat, Books = book);
    }

然后你就能够访问页面上的所有内容了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接