开发者

In asp.net mvc 2 : how to access http post data inside constructor of any controller

开发者 https://www.devze.com 2023-01-26 18:17 出处:网络
My controller has abstract base controller. I want to access the form post data inside abstract base class constructor. How can we do that ?

My controller has abstract base controller. I want to access the form post data inside abstract base class constructor. How can we do that ?

public abstract class AppController : Controller  
{  
    public AppController()   
    {
        // request post data required here  
    }  
}  

public class ProductController : AppController  
{  
  开发者_如何学编程  public ProductController() {  }  
}  

Purpose : Updating second dropdown on change of first dropdown. Both are on MASTER page.

Code given above is one of the 2 options to pass data to master page:

  1. Add using ViewData in ALL the action methods.
  2. Do it in only one place using abstract base controller - add the required data using ViewData inside its constructor and make our main controller class implement this abstract base controller class. So that we don't have to add the viewdata for master page in all action methods.


I don't know what is your final goal with this but this is something which is not recommended to be done in MVC. The Request object is not yet initialized in the constructor of the controller. You could try to use the native HttpContext object:

string foo = System.Web.HttpContext.Current.Request["foo"];

but that's something extremely bad and I would never recommend you doing this as now your controller is coupled to the static native HttpContext instance without any chance of unit testing it.

Instead of using the constructor you could override the Initialize method of your controller where you will have access to the request context and you could read posted data:

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);
    string foo = requestContext.HttpContext.Request["foo"];
}
0

精彩评论

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