On All Things Web

Feb 21

I really love the Action syntax, which has been made pretty popular with ASP.NET MVC because of its support for providing a customized template (see implementations of this in the MVC Contrib project and Telerik’s ASP.NET MVC framework, both which are open source).  Actions come in vary handy because they can affect the response stream in web applications, as illustrated in the following brief example that comes from the Telerik framework.


<% Html.Telerik().PanelBar().Name(“PanelBar”).Items(items =>       
{
            foreach (var i in Model) {
                  items.Add().Text(“Products > Books”).Content(() =>
                  {
                       %>
                          <div>
                                 <strong><%= i.Title %></strong><br/>
                                 <%= i.Description %>
                          </div>
                      <%
                 }
            }
}).Render(); %>


The action provides a content for each of the Panel bar items.  At rendering time, the custom action method supplied can be invoked, and the results are written to the underlying HTML response stream.  Action helps provide a customized template that leverages the ability to render and process HTML out of the box with no additional logic needed.


Actions can also help you work in a vacuum.  Consider this next segment:


NUnitExceptionTester.CheckException(true, () => { list.AppendAttributes(default(IDictionary<string, object>)); });


This is part of the Nucleo.NUnit component I recently released for the Nucleo framework 0.5.  This helper object checks to see if an exception was thrown.  The first param specifies that we are looking for an exception to happen (false is the opposite, that an exception shouldn’t happen).  The action specifies the content to run, which may in fact throw an exception.  If an exception is thrown, the CheckException method catches it and handles evaluating the response based on the other criteria.


So you can see how the Action  class or its genericized forms can be useful to you.  Note: if you were wondering the differences of the action class and each genericized form, the core action class takes no parameters, while the generic forms actually specify the parameters that must be passed in.  So Action<string, int> requires the syntax to define two parameters, as in (s, i) => { .. } and so on.  There are quite a few overloads available to you.  Additionally, Actions return no value to the caller, whereas it’s the purpose of lambda expressions to return a value, that is one significant difference between the two syntaxes.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>