c# - MVC View 继承

标签 c# asp.net-mvc model-view-controller inheritance

例如: 假设我想返回一个显示汽车列表的 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/

相关文章:

c# - MVC 构建 - 根据构建配置编辑连接字符串文件 (VS2012)

c# - 当我在表单 onsubmit 中有函数时,Ajax 不起作用

asp.net-mvc - 订阅 ServiceBus 以获取通知

java - Spring @ModelAttribute 接口(interface)

c# - 无法向 Unity 和 Entity Framework 注册 DbConnection

c# - 如何在没有url编码的情况下允许&在带有西类牙字符的url中的单词之间

ruby-on-rails - 使用 rails 和backbone.js 使我的应用程序更加干燥

c# - Serilog 不记录信息日志

c# - 通过 C# 进行 Windows 桌面搜索

c# - 从 WCF 服务转换类型