【发布时间】:2009-08-28 00:02:18
【问题描述】:
以下是我的解决方案的一些背景知识:
- ASP.Net MVC 应用程序
- 将 Linq-to-SQL 与逐层表继承结合使用
- 默认使用 DataAnnotationsModelBinder
所以我有一个Device 抽象类,然后是一系列派生类(ServerDevice、DiskDevice、PSUDevice 等),它们以被禁止的 Linq-to-SQL 方式从它继承。我有一个控制器来处理所有这些不同的相关模型类型,它会根据类型呈现不同的部分,并通过一个方便的下拉菜单来选择它们。我的 (GET) Create 方法如下所示:
// GET: /Devices/Create/3
public ActionResult Create(int? deviceTypeID)
{
return View(DeviceFactory(deviceTypeID);
}
DeviceFactory 是一个静态方法,它返回一个基于 int 鉴别器的派生类的新实例。 POST Create 方法如下所示:
// POST: /Devices/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([ModelBinder(typeof(DeviceModelBinder))]Device device)
{
if (!ModelState.IsValid)
return View(device);
_repository.Add(device);
_repository.Save();
TempData["message"] = string.Format("Device was created successfully.");
return RedirectToAction(Actions.Index);
}
我的自定义模型绑定器如下所示:
public class DeviceModelBinder : DataAnnotationsModelBinder
{
private readonly Dictionary<string, Type> _deviceTypes =
new Dictionary<string, Type>
{
{"1", typeof (ServerDevice)},
{"2", typeof (DiskDevice)}
// And on and on for each derived type
};
protected override object CreateModel(ControllerContext controllerContext,
ModelBindingContext bindingContext, Type modelType)
{
return base.CreateModel(controllerContext, bindingContext,
_deviceTypes[bindingContext.ValueProvider["deviceTypeID"].AttemptedValue]);
}
}
所以在尝试了一天之后,阅读了有关 ActionInvoker、自定义 ActionFilters 和各种其他 MVC 内容的信息,我想知道我得出的解决方案是否是一个好的解决方案。帮助减轻我对错过一些非常明显的概念并重新发明轮子的恐惧。 有更好或更简洁的方法吗?
谢谢!
【问题讨论】:
标签: asp.net-mvc linq-to-sql inheritance binding model