2013-02-18 87 views
0

我需要在我的视图中有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]'. 

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

UPDATE

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); 

     } 
+1

发布您的控制器代码。 – 2013-02-18 21:54:29

+0

您在这个'@model Tuple '代码行中的答案。 – sigod 2013-02-18 21:56:21

+0

对不起@EricJ。我误解了,你是对的。 – 2013-02-18 21:58:08

回答

1

有问题的视图被从仅通过在My.Models.Mod2而非Tuple<My.Models.Mod1,My.Models.Mod2>控制器动作调用。

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

UPDATE

控制器代码

return View(model1,model2); 

应该

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

你传入MODEL1和MODEL2作为单独的参数,而不是作为一个元组。

+0

我已编辑我的代码,但它仍然无法正常工作。 – 2013-02-18 22:07:18

+0

根据您发布的控制器代码更新了我的答案。 – 2013-02-18 23:29:27

0

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

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

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

但是,我会建议创建一个新的模型,其他模型作为属性。

+1

我同意试图破解多个模型并不是一个好主意,并且会变得很难维护,所以最好查看一下使用renderpartial/renderaction – 2013-02-18 23:31:19

1

生成包含这两个视图模型:

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

然后构建并传递CompositeViewModel查看。设置视图以使用CompositeViewModel作为模型@model CompositeViewModel

使用元组不容易让您扩展或更改您正在执行的操作。

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

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

相关问题