Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC ActionFilter parameter binding

If you have a model-bound parameter in an action method, how can you get to that parameter in an action filter?

[MyActionFilter]
public ActionResult Edit(Car myCar)
{
    ...
}

public class MyActionFilterAttribute : ActionFilterAttribute
{
    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //I want to access myCar here
    }

}

Is there anyway to get myCar without going through the Form variables?

like image 237
Shlomo Avatar asked Dec 25 '09 16:12

Shlomo


People also ask

Does MVC use data binding?

MVC doesn't use data bindings like old web api. You have to use model bindings in a MVC or MVVM approach.

What is binding in ASP.NET MVC?

What Is Model Binding? ASP.NET MVC model binding allows mapping HTTP request data with a model. It is the procedure of creating . NET objects using the data sent by the browser in an HTTP request. Model binding is a well-designed bridge between the HTTP request and the C# action methods.

What is parameter binding?

A parameter binding is a piece of information that is transmitted from the origin to the destination of a flow. A parameter binding has a name and a value, which is obtained at its origin component. A flow may have a multiple parameter binding, passing a set of values instead of a single one.


1 Answers

Not sure about OnActionExecuted but you can do it in OnActionExecuting:

public class MyActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // I want to access myCar here

        if(filterContext.ActionParameters.ContainsKey("myCar"))
        {
            var myCar = filterContext.ActionParameters["myCar"] as Car;

            if(myCar != null)
            {
                // You can access myCar here
            }
        }
    }
}
like image 121
eu-ge-ne Avatar answered Sep 28 '22 08:09

eu-ge-ne