我们可以在视图中拥有多个模型吗? [英] Can we have multiple models in a view ?

查看:95
本文介绍了我们可以在视图中拥有多个模型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以通过将一个List属性保存到另一个中来完成,如下所示:



 Class Customer 
{
public string 名称{ get < /跨度>; set ;}
公开列表<地址>地址{获取; set ;}

}

类地址
{
public string StreetNo { get ; set ;}
public string HouseNo { get ; set ;}
}





然后,@ model View中的Customer和@ Model.Name和@foreach(地址中的var项目){item.StreetNo}来呈现值或保留ViewModel或ModelBinder。



但是我的具体问题是如果我在下面的视图中保持如下,



@model客户

@model地址

- 在Customer =>以下模型类的Index.cshtml。



 Class Customer 
{
public string 名称{ get ; set ;}

}

类地址
{
public string StreetNo { get ; set ;}
public string HouseNo { get ; set ;}
}





无效。为什么?



在这种情况下,相同的视图应该呈现两个不同的模型对象和我的CustomerController => Action方法()我将根据条件(if / else)返回Customer或Address对象。我不想使用局部视图。



具体问题是为什么我们在视图中不能有两个模型? MVC内部如何停止这样做/不接受这样做?



任何指导都是适合的。

解决方案

尝试使用这些链接获取指导 -

ASP.NET MVC 4 / MVC 5视图中的多个模型 [ ^ ]

如何选择在ASP.NET MVC中传递多个模型的最佳方式 [ ^ ]

I know that it can be done by keeping one List property into another, Like Below:

Class Customer
{
 public string Name {get; set;}
 Public List<Address> Address {get; set;}

}

Class Address
{
 public string StreetNo {get; set;}
 public string HouseNo {get; set;}
}



And then, @model Customer in View and @Model.Name and @foreach(var item in Address){item.StreetNo} to render values or keeping a ViewModel or ModelBinder.

But my specific question is if I keep like below in a view,

@model Customer
@model Address
-- in Customer => Index.cshtml for the below model classes.

Class Customer
{
 public string Name {get; set;}

}

Class Address
{
 public string StreetNo {get; set;}
 public string HouseNo {get; set;}
}



Will not work. Why ?

In this case, the same view should render for two different model objects and in my CustomerController => Action method() I will either return Customer or an Address object based on condition(if/else). I do not want to use partial view.

The specific question is Why we can not have two models in a View ? How MVC internally stops to do this/not accept to do this ?

Any guidence would be appriciable.

解决方案

Try these links for guidance -
Multiple Models in a View in ASP.NET MVC 4 / MVC 5[^]
How to Choose the Best Way to Pass Multiple Models in ASP.NET MVC[^]


这篇关于我们可以在视图中拥有多个模型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆