开发者

How do I access the model and Metadata within a custom ActionFilterAttribute?

public class CheckMetadataAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // get model
        // get metadata for each model property
        // set viewdata if metadata X exists
    }
}

Old question 开发者_如何学运维was: How do I access ViewData within a custom ModelMetadataProvider? That was a no go.


You can't/should not access ViewData or any HttpContext related info in a model metadata provider.


UPDATE:

After the updated question things start to make a little sense, so let's update the answer:

public class CheckMetadataAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {

        // get model?
        var result = filterContext.Result as ViewResultBase;
        if (result != null)
        {
            var model = result.Model;
            if (model != null)
            {
                // get metadata for model (you have a single model, no idea what you meant by "for each model" in your question)
                var metadata = ModelMetadataProviders.Current.GetMetadataForType(null, model.GetType());
                if (metadata.DisplayName == "foo bar")
                {
                    // set viewdata if metadata X exists
                    filterContext.Controller.ViewData["foo"] = "bar";
                }
            }
        }
    }
}    

This being said, obviously, using ViewData in an ASP.NET MVC application is something that I absolutely recommend against. ViewData is weakly typed. Whatever you are trying to achieve (would have been nice by the way if you have explained what is your goal), don't use ViewData, use view models and strongly typed views.

Personally I am allergic to things like ViewBag/ViewData in ASP.NET MVC applications. When I do code reviews and see people using them I know they did something wrong.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜