当我熟悉Asp.Net MVC时,我使用的是MVC 2,我注意到在Kigg项目中使用了BaseViewData类,我不确定如何实现.
我希望我的每个viewmodels都有一些可用的值.使用一个迭代表,但我想知道最好的做法是什么,Kigg如何做?
Kigg
public abstract class BaseViewData { public string SiteTitle { get; set; } // ...other properties } public class UserListViewData : BaseViewData { public string Title { get; set; } // .. other stuff }
在我的WebForms应用程序中,我使用从System.Web.UI.Page继承的BasePage.
所以,在我的MVC项目中,我有这个:
public abstract class Baseviewmodel { public int SiteId { get; set; } } public class Userviewmodel : Baseviewmodel { // Some arbitrary viewmodel } public abstract class BaseController : Controller { private IUserRepository _userRepository; protected BaseController() : this( new UserRepository()) { } }
参考Kigg方法,我如何确保从Baseviewmodel继承的每个viewmodel都具有SiteId属性?
我应该使用什么最佳做法,样本或模式?
解决方法
我将采取的方法是使用基本控制器,并使用OnActionExecuted覆盖用普通数据填充您的模型.然后只需确保您的控制器从您的基本控制器继承,并且模型从基本模型继承.
public class BaseController : Controller { public override void OnActionExecuted( ActionExecutedContext filterContext ) { var result = filterContext.Result as ViewResult; if (result != null) { var baseModel = result.Model as Baseviewmodel; if (baseModel != null) { baseModel.SiteID = ... } } } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。