开发者

Extend ASP.NET MVC ViewResult with Custom Properties

For my asp.net mvc project, whenever I return a view, I append a couple of properties in a base controller by overriding the OnActionExecuted method like so:

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if(filterContext.Result.GetType() == typeof(ViewResult))
        {
            var action = filterContext.Result as ViewResult;
            action.ViewBag.ClientSettings = ClientSettings;
        }

        base.OnActionExecuted(filterContext);
    }

I'm currently sticking the ClientSettings in the ViewBag and then accessing it in the view from the 开发者_JAVA技巧viewbag.

What I would really like is for the action itself to have the ClientSettings property directly on the ViewResult so that I can in turn, access it directly from the view but I'm not quite sure how to do this?


We are using strongly typed views and store things like you described in model properties.

Your case (base controller code):

protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
    var viewModel = filterContext.Controller.ViewData.Model as ViewModelBase;
    if (viewModel != null)
    {
        viewModel.ClientSettings = ClientSettings;
    }

    base.OnActionExecuted(filterContext);
}

Now if your view model is inherited from ViewModelBase you can set ClientSettings from the base controller and access it in your views via Model property of ViewPage<T>.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜