Asp.net-Mvc-2

如何在 Asp.net MVC 2 中使用基本 ViewModel

  • January 13, 2012

當我熟悉 Asp.Net MVC 時,我正在使用 MVC 2,我注意到在 Kigg 項目中使用了 BaseViewData 類,我不確定如何實現。

我希望我的每個 ViewModel 都有某些可用的值。我想到了使用 iterface,但我想知道最佳實踐是什麼以及 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 = ...
            }
       }
   }
}

引用自:https://stackoverflow.com/questions/2751225