我正在尝试将两个模型传递到局部视图中。问题是在我的View中我只能找到:“Model.Class1”和“Model.Class2”,而我实际上想要得到Model.Class2.UserID ..
我确实得到了它的工作,但后来它抱怨GetEnumerator()或其他东西。还尝试了元组,对我来说根本没用。对ASP NET MVC来说非常新,所以非常棒! :)请回复!
模特课:
public class Class1ANDClass2
{
public IEnumerable<Klubben.Models.Class1> class1 { get; set; }
public IEnumerable<Klubben.Models.Class2> class22{ get; set; }
}
我的观点:
@model IEnumerable<Klubben.Models.Class1ANDClass2>////(Contains classes Omraade and Medlem)
@foreach (var item in Model)
{
if(item.Class1.UserID >= 1) ////This does not work, which i need it to do
///For example show item.Class2.Username
}
我的控制器:
public ActionResult PartialView()
{
try
{
IEnumerable<Class1> c1 = some object
IEnumerable<Class2> c2 = some object
Class1ANDClass2 omt= new Class1ANDClass2();
omt.Class1 = c1
omt.Class2 = c2;
return PartialView("MyPartial", omt);
}
catch (Exception feil)
{
return PartialView("exception");
}
}
答案 0 :(得分:3)
问题在于你的循环
@model IEnumerable<Klubben.Models.Class1ANDClass2>////(Contains classes Omraade and Medlem)
@foreach (var item in Model.class1)
{
if(item.UserID >= 1) ////This does not work, which i need it to do
///For example show item.Username
}
// similarly for class2
@foreach (var item in Model.class2)
{
if(item.aProperty >= 1) ////This does not work, which i need it to do
///For example show item.otherProperty
}
答案 1 :(得分:0)
您正在从action方法返回一个名为omt的对象。但是你的观点是期待IEnumerable。
将视图模型声明更改为
**@model Klubben.Models.Class1ANDClass2**
@foreach (var item in Model.Class1)
{
if(item.Class1.UserID >= 1) ////This does not work, which i need it to do
///For example show item.Class2.Username
}
答案 2 :(得分:0)
您可以使用元组访问视图中的多个模型,如下所示:
@model Tuple<FirstModel, SecondModel>
<div>
@Model.Item1.FirstModelProp
@Model.Item2.SecondModelProp
</div>