例如: 假设我想返回一个显示汽车列表的 View ,还显示您所在地区的一部分经销商。这是两个脱节的数据。
我的 View 继承了如下汽车列表:
public partial class CarLot : ViewPage<List<Cars>>
{
}
现在我可以从 Controller 返回 View ,如下所示:
return View(Model.GetCars());
为了呈现这个,我的标记看起来像下面这样:
<% foreach (Car myCar in ViewData.Model)
{some html here}
%>
这会处理汽车列表,但我的问题是,我如何处理经销商列表? View 是否支持多重继承,或者我是否必须再次点击模型形成标记?我知道可以这样做,但不确定这是否是最佳做法。
最佳答案
创建数据传输对象
public class CarLotViewModel
{
public List<Car> Cars { get; set; }
public List<Dealer> NearbyDealers { get; set; }
}
将 View 设置为使用 View 模型:
public partial class CarLot : ViewPage<CarLotViewModel>
{
}
然后在你的 Controller 中:
var model = new CarLotViewModel();
model.Cars = GetCars();
model.NearbyDealers = GetDealers();
return View(model);
然后在你的 View 中枚举每个集合:
<% foreach (Car car in ViewData.Model.Cars) { %>
....
<% foreach (Dealer dealer in ViewData.Model.NearbyDealers) { %>
关于c# - MVC View 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/422342/