Reputation: 4376
Is there any way to get access to the current 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?
Upvotes: 1
Views: 2058
Reputation: 665
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);
Upvotes: 2
Reputation: 1502
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.
Upvotes: 0