在我的ASP.Net MVC 3项目中,我想有一个基类模型对象,它具有某些属性,然后我将在我的应用程序中的所有其他模型中使用(或至少其中大部分)。这样,使用这些派生模型的视图也将具有基类模型属性。从另一个模型导出模型
基类模型属性可以在基类控制器中设置,然后以某种方式我需要用相同的数据填充派生模型。关于如何最好地完成任务的任何建议?
或者我应该考虑以某种方式创建我自己的DefaultModelBinder?我对这里的选择有些困惑。就好像你不能说。 :)
示例代码
基本型号
public class ElkModel
{
public bool IsAdministrator { get; set; }
}
衍生型号
public class UserModel : ElkModel
{
[HiddenInput]
public int User_ID { get; set; }
// Other properties specific to this model
}
因此,在基本控制器
private BaseModel baseModel;
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
baseModel = new baseModel();
baseModel.MyProperty = "test";
base.OnActionExecuting(filterContext);
}
而派生控制器的操作方法
public ActionResult Index()
{
// Derives from the base model in the base controller
UserModel model = new UserModel();
// model.IsAdministrator where IsAdministrator is a property of the base Model not UserModel
return View(model);
}
嗨保罗,感谢您的快速响应。我认为我们只在这里处理输入Model/ViewModels。我将使用基本模型属性来触发页面上的某些显示(例如,Model.IsAdministrator)。 – beaudetious 2011-01-25 16:04:17
好吧,所以我明白我将如何使用,例如,重写(是一个单词?)基本控制器中的OnActionExecuting方法。我有一个模型类作为该控制器的私有成员,并相应地填充它的属性。我将如何将基础模型属性导入我的模型中。在原始问题中查看我上面更新的代码示例。 – beaudetious 2011-01-25 16:11:38