开发者

ModelState.IsValid with custom view result

开发者 https://www.devze.com 2023-04-07 12:05 出处:网络
I\'ve created a custom view result that inherits from ViewResult. In my controller I check if ModelState.IsValid and then return my custom view. I\'m finding that the errors don\'t seem to be making i

I've created a custom view result that inherits from ViewResult. In my controller I check if ModelState.IsValid and then return my custom view. I'm finding that the errors don't seem to be making it to the view. Here's my view result:

public class EnrichedViewResult<T> : ViewResult
{
    public EnrichedViewResult(string viewName, T model)
    {   
        this.ViewName = viewName;
        this.ViewData.Model = model;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        base.ExecuteResult(context);
    }
}

And the method I'm calling on my controller:

    public EnrichedViewResult<T> EnrichedView<T>(string viewName, T model)开发者_Go百科{
        return new EnrichedViewResult<T>(viewName, model);
    }

When I inspect ControllerContext.Controller.ViewData.ModelState in ExecuteResult the ModelState contains errors as I would expect.

[Update]

@Andras was spot on. I needed to pass the ViewData from my controller rather than just a model. Easiest way was to grab my base controller's ViewData property (same as what ASP.NET MVC use for the ViewResult helper methods. I changed my custom ViewResult to accept a ViewDataDictionary and my helper methods to below:

    public EnrichedViewResult<T> EnrichedView<T>(string viewName, T model){
        if (model != null) {
            ViewData.Model = model;
        }
        return new EnrichedViewResult<T>(viewName, ViewData);
    }


I think you should be passing in a ViewData object to your result; since that is the container of ModelState; not simply the Model. Typically you then shortcut the creation/passing of the ViewData by using the Controller's ViuewData as a starting point, writing in the model (check out the base controller).

From this code it doesn't there's any way ModelState could make it to the view.

0

精彩评论

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

关注公众号