开发者

How to get access to FormCollection, ViewData, and ModelState

开发者 https://www.devze.com 2023-03-28 06:00 出处:网络
Is there any way to get access to the curren开发者_开发问答t running request\'s FormCollection, ViewData, ModelState, etc. when running in an ASP.NET MVC application other than if you are directly wor

Is there any way to get access to the curren开发者_开发问答t running request's FormCollection, ViewData, ModelState, etc. when running in an ASP.NET MVC application other than if you are directly working in the View? I'd like to be able to call some custom handlers from within the view, but access these collections without having to pass them. I'm thinking something similar to HttpContext.Current in webforms?


Try,

        var wrapper=new HttpContextWrapper(System.Web.HttpContext.Current);
        var routeData = RouteTable.Routes.GetRouteData(wrapper);
        Controller con = (Controller)ControllerBuilder.Current.GetControllerFactory().CreateController(new RequestContext(wrapper, routeData), routeData.Values["controller"].ToString());
        var viewData = con.ViewData;
        var modelState= con.ModelState;
        var form=new FormCollection();
        var controllerContext = new ControllerContext(wrapper, routeData, con);
        Predicate<string> propertyFilter = propertyName => new BindAttribute().IsPropertyAllowed(propertyName);
        IModelBinder binder = Binders.GetBinder(typeof(FormCollection));
        ModelBindingContext bindingContext = new ModelBindingContext()
        {
            ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => form, typeof(FormCollection)),
            ModelName = "form",
            ModelState = modelState,
            PropertyFilter = propertyFilter,
            ValueProvider = ValueProviderFactories.Factories.GetValueProvider(controllerContext)
        };
        form = (FormCollection)binder.BindModel(controllerContext, bindingContext);


There is a ViewContext object that lets you link back to most of what you're asking for, but you really have to ask yourself why you're doing all of this in the view. (IMHO anyway)

Edit: I may have misread your question. There is a ControllerContext in the controller and a ViewContext in the view. Most of the extensibility points in MVC have some sort of Context object that lets you get at the Request and it's data.

0

精彩评论

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

关注公众号