Default parameter in all action before action executing in mvc

299 Views Asked by At

Is there a way to add some default parameter to every action in MVC application. So I can get the value of the parameter if send from anchor href.

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
      int currentformcontrolid = 0;
       foreach (var parameter in filterContext.ActionParameters)
       {
           if (parameter.Key == "FormControlID")
           {
               currentformcontrolid = Int32.Parse(parameter.Value.ToString());
           }
       }
}

and my href like this (it's an AJAX anchor call) :

<a 
  data-ajax="true" 
  data-ajax-method="GET" 
  data-ajax-mode="replace" 
  data-ajax-update="#soapfunction-screens" 
  href="/Patient/Intake?FormContorlID=100003"
  data-islandingpage="False"
  id="InkAlcoholDrug" >
    Alcohol Drug Use 
</a>

and my action like (can be any action in the application, every single action should have that parameter FormControlID

public ActionResult WhatEverAction(int TestID=0)
{

}

In OnActionExecuting i can only access TestID but not the parameter of href that is FormControlID

3

There are 3 best solutions below

9
On

You can access the query string values from the Request property of the HttpContext property

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    int currentformcontrolid = Convert.ToInt32(filterContext.HttpContext
       .Request.QueryString["FormControlID"].ToString());
}
1
On

You can try specifying that parameter in route:

routes.MapRoute(
    name: “Default”,
    url: “{controller}/{action}/{FormControlID}”,
    defaults: new { controller = “Home”, action = “Index”, FormControlID = UrlParameter.Optional }
);
1
On

Try this

protected override void OnActionExecuted(ActionExecutedContext filterContext)
{

    string FormControlID = filterContext.RequestContext.HttpContext.Request["FormControlID"];

    base.OnActionExecuted(filterContext);
}

enter image description here