添加Razor关键字

时间:2016-05-17 04:55:00

标签: asp.net-mvc razor

扩展Razor视图引擎以添加其他关键字的最佳流程是什么?

我不是dynamic ViewBag属性的粉丝,因此对于我的所有页面,我都定义了强类型ViewModel POCO,但也定义了强类型ViewData对象:

public abstract class BaseViewData<TModel,TController> : ViewDataDictionary<TModel>

TController被指定为可选地允许对父Controller进行强类型回调

这样我就可以拥有经过编译时验证的成员,例如String PageTitle(在站点范围内的基类中)和每页成员 - 它与ViewModel协同工作:BaseViewData -subclass包含单向数据,ViewModel - 类包含双向数据。当您调整MSBuild系统以将视图预编译到输出程序集中时,这非常有用 - 不再需要.aspx.cshtml个文件!

在ASP.NET MVC中(使用WebForms视图引擎)我有自己的基类ViewPage子类:

public class ViewPage2<TViewModel,TViewData> : ViewPage<TModel> where TViewData : ViewDataDictionary<TModel> {

    private TViewData _data;

    public new TViewData ViewData {
        get {
            if( _data == null ) {
                _data = (TViewData)base.ViewData;
            }
            return _data;
        }
    }
}

我最近把它带到了Razor,很容易做到:

public abstract class WebViewPage2<TViewModel,TViewData> : WebViewPage<TModel> where TData : ViewDataDictionary<TModel> {
    // same ViewData property code as above
}

.cshtml文件中,您可以使用@inherits razor关键字手动指定基类 - 这需要完全限定的具体通用类型名称 - 但您也可以省略@inherits而是指定@model关键字,Razor将TModel参数传递给WebViewPage<TModel>

当我的基类添加第二个泛型类型参数时,我宁愿不必输入我的.cshtml文件:

@inherits MyNamespace.WebViewPage2<MyOtherNameSpace.Views.FooViewModel,MyOtherNameSpace.Views.FooViewData>

...而是这样做:

的Web.config

<system.web.webPages.razor>
    <pages pageBaseType="MyNamespace.WebViewPage2">
        ...

MyPage.cshtml

@model FooViewModel
@data FooViewData

但是这需要以某种方式扩展Razor View引擎 - 但这是不明显的,因为它需要扩展Razor解析器本身,因此它识别@data TViewData并将其作为第二个类型参数传递。

1 个答案:

答案 0 :(得分:0)

你可以像这样实现一个继承的ViewClass(小心命名空间,不能改变它):

namespace System.Web.Mvc {
     public abstract class WebViewPage<TViewModel, TModel> : WebViewPage<TModel> where TViewModel : class {
         private TViewModel _viewModel;

         public TViewModel ViewModel {
             get {
                 if (_viewModel == null) {
                    throw new InvalidOperationException("No ViewModel defined for this View.");
                 }
                 return _viewModel;
             }
             set { _viewModel = value; }
         }

         public override void InitHelpers() {
              base.InitHelpers();

              if (this.ViewBag.ViewModel == null) {
                 // No ViewModel defined => set null.
              }
              else if (!(this.ViewBag.ViewModel is TViewModel)) {
                 throw new InvalidOperationException(string.Format("The specified ViewModel value is of type '{0}' and must be of type '{1}'.", this.ViewBag.ViewModel.GetType(), typeof(TViewModel)));
             } else {
                _viewModel = this.ViewBag.ViewModel;
             }
        }
    }
}

然后你不必更改web.config或其他任何东西,并可以像这样实例化视图:

 @model ViewModelType, (Input?)ModelType

然后通过@ViewModel在视图中提供键入的ViewModel(ViewModelType类型)。 类型(输入)ModelType的模型仍然可以通过@Model像往常一样。