Tallan's Blog

Tallan’s Experts Share Their Knowledge on Technology, Trends and Solutions to Business Challenges

Posts Tagged "mvc"

Global Action Filters in ASP.NET MVC 3

Action Filters are a great way to handle cross-cutting concerns in ASP.NET MVC such as Logging, ExceptionHandling, etc.  In previous versions of MVC3, action filters have to be explicitly added to each controller.
MVC3 adds the concept of Global Action Filters which allow you to apply action filters globally without the need for explicit declaration.  In this example, we’ll demonstrate how to add a debug action filter attribute that shows debug information for each view using Global Action Filters.

Code Snippet

/// <summary>
    /// Displays the elapsed time and environment for each executed action in the HTTP Response Stream.
    /// </summary>
    public class DebugInfoAttribute : ActionFilterAttribute
        readonly Stopwatch _startWatch = new Stopwatch();
        private static string _outputFormat = “<h4>Debug Environment Info</h4><div class=\”debuginfo\”><table><tr><td>Web Server:</td><td>{0}</td></tr><tr><td>Browser:</td><td>{1}</td></tr><tr><td>Controller</td><td>{3}</td></tr><tr><td>Action:</td><td>{4}</td></tr><tr><td>Execution Time(ms):</td><td>{5}</td></tr></table></div>”;
        public override void OnActionExecuting(ActionExecutingContext filterContext)

        public override void OnResultExecuted(ResultExecutedContext filterContext)
            var browser = filterContext.HttpContext.Request.Browser;
                                                                   String.Format(“{0} ({1})”,browser.Browser,browser.Version),


This action filter uses the StopWatch object to clock how long the action took…

Uploading file: the .NET MVC way

In ASP.NET, the traditional way of uploading files is as follows.
<form id=”form1″ runat=”server”>
<asp:FileUpload ID=”FileUpload1″ runat=”server” />
<asp:Button ID=”Button1″ runat=”server” Text=”Upload”
OnClick=”Button1_Click” /></p>
<asp:Label ID=”Label1″ runat=”server”></asp:Label></p>
And you have access to the uploaded file like this.
protected void Button1_Click(object sender, EventArgs e)
In .NET MVC, you can achieve the same with the following code.
<form action=”/controller/action/” accept-charset=”UNKNOWN” enctype=”multipart/form-data” method=”post”>
<label for=”file1″>file1</label>
<input id=”file1″ name=”file1″ size=”20″ type=”file” />
The controller side
foreach (string fileName in Request.Files)
HttpPostedFile file = Request.Files[fileName ];
It is important to understand the fundamental difference between the traditional web-form based .NET programming methods and the .NET MVC methods. You can still use the server controls, but you can only use them for read-only data rendering purpose, since ViewState is no longer an option in .NET MVC.