Reputation: 79
I've just started a new project in ASP.net 4.0 with MVC 2.
What I need to be able to do is have a custom hook at the start and end of each action of the controller.
e.g.
public void Index() {
*** call to the start custom hook to externalfile.cs (is empty so does nothing)
ViewData["welcomeMessage"] = "Hello World";
*** call to the end custom hook to externalfile.cs (changes "Hello World!" to "Hi World")
return View();
}
The View then see welcomeMessage as "Hi World" after being changed in the custom hook.
The custom hook would need to be in an external file and not change the "core" compiled code. This causes a problem as with my limited knowledge ASP.net MVC has to be compiled.
Does anyone have any advice on how this can be achieved?
Thanks
Upvotes: 1
Views: 1599
Reputation: 1744
You create your own class based on the ActionFilterAttribute. It has the following hooks.
For example,
public class MyFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var controller = filterContext.Controller;
controller.ViewData["welcomeMessage"] = "Hi World!";
controller.TempData["Access_My_TempData"] = "Some Value";
base.OnActionExecuted(filterContext);
}
}
You can also check what type of [Action] the Action method is performing.
if ((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult))
{
// do something only if we are redirecting to a different action
}
else if (filterContext.Result is ViewResult)
{
// this is just a normal View action
}
Oh I forgot to show how to use the attribute.
You just decorate on top of your Action Method.
[MyFilterAttribute]
public ActionResult MyActionMethod()
{
return View();
}
Upvotes: 3
Reputation: 10443
How about override OnActionExecuting/OnActionExecuted and use MEF(Import,Export other assembly code)?
Upvotes: 0
Reputation: 994
An event based plugin system where you can dynamically call script code. So creating (for example) iron python scripts that get called when events are raised by the controller.
Doesn't have to be iron python, but that would make the most sense that I can see.
Upvotes: 1