如何使用基本的ViewModel在Asp.net MVC 2 [英] How to use a Base ViewModel in Asp.net MVC 2

查看:185
本文介绍了如何使用基本的ViewModel在Asp.net MVC 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我自己熟悉与Asp.Net MVC,我使用MVC 2,我已经注意到Kigg项目,我不能确定如何实现使用BaseViewData类。

As I familiarize myself with Asp.Net MVC, I am using MVC 2, I have noticed the use of a BaseViewData class in the Kigg project which I am unsure how to implement.

我希望我的每一个的ViewModels中有可用的某些值。使用iterface想到的,但我想知道最好的做法是什么,不Kigg怎么做呢?

I want each of my ViewModels to have certain values available. Using an iterface comes to mind but I am wondering what the best practice is and how does Kigg do it?

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项目,我有这样的:

In my WebForms application I use a BasePage that inherits from System.Web.UI.Page.
So, in my MVC project, I have this:

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方法,我该如何确保每个我的ViewModel的从BaseViewModel继承有SITEID财产?

Referencing the Kigg methodology, how do I make sure that each of my ViewModel that inherits from the BaseViewModel have the SiteId property?

什么是我应该使用的最佳实践,样品或模式?

What is the best practice, samples or patterns I should be using?

推荐答案

这是我会采取的方法是使用一个基控制器,以及和使用OnActionExecuted覆盖来填充通用数据模型。然后,只需确保你的控制器从基本控制器继承和你的模型从基础模型继承。

The approach that I would take is to use a base controller as well and use the OnActionExecuted override to populate your model with common data. Then just make sure that your controllers inherit from your base controller and your models inherit from the base model.

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 = ...
             }
        }
    }
}

这篇关于如何使用基本的ViewModel在Asp.net MVC 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆