尝试将多个模型添加到视图时出错

本文关键字:视图 出错 添加 模型 | 更新日期: 2023-09-27 18:00:12

我的视图中需要2个models。但由于我们只能添加1个视图,我采取了以下方法;

@model Tuple<My.Models.Mod1,My.Models.Mod2>
    @Html.DropDownListFor(m => m.Item2.humanKind,Model.Item2.allHuman)

    @Html.TextBoxFor(m => m.Item1.food)

但是,我最终得到的是以下错误;

The model item passed into the dictionary is of type 'My.Models.Mod2', but this dictionary requires a model item of type 'System.Tuple`2[My.Models.Mod1,My.Models.Mod2]'.

这是什么,我该如何解决?

更新

 public ActionResult Index()
        {
            var model2 = new Mod2 { allHuman = allHumans() };
            var model1 = new Mod1(); // JUST NOW I ADDED THIS, BUT IT DOESn't WORK
            return View(model1,model2);
        }

尝试将多个模型添加到视图时出错

每个视图只能有一个模型。你需要按照Ufuk的建议实例化Tuple。

然而,我建议创建一个新模型,将其他模型作为属性。

有问题的视图是从只传入My.Models.Mod2而不是Tuple<My.Models.Mod1,My.Models.Mod2>的控制器操作中调用的。

仔细检查调用此视图的特定控制器操作。

更新

您的控制器代码

return View(model1,model2);

应该是

return View(new Tuple<My.Models.Mod1,My.Models.Mod2>(model1, model2>);

您将模型1和模型2作为单独的参数传递,而不是作为元组传递。

构建一个包含以下两者的视图模型:

Public class CompositeViewModel{
 Public Mod1 mod1 {get;set;}
Public Mod2 mod2 {get;set}
}

然后构造并将CompositeViewModel传递给视图。将视图设置为使用CompositeViewModel作为模型@model CompositeViewModel

使用Tuple并不容易让你扩展或改变你正在做的事情。

它甚至可能看起来像是有一个包含数据的ViewModel,然后是一些相关的IEnumerable<SelectListItem>。如果是这种情况,那么将ViewModel命名为CreateAnimalTypeViewModel,其中包含创建它所需的所有属性,然后有各种选择列表。

如果您需要从某个项目映射到ViewModel,例如,如果您正在编辑现有项目,则可以使用AutoMapper。

在将元组实例发送到视图之前,您没有创建元组实例。

public ActionResult Index()
{
    var model2 = new Mod2 { allHuman = allHumans() };
    var model1 = new Mod1();
    return View(new Tuple<Mod1,Mod2>(model1,model2));
}