MVC - Expression Language and custom tags

I have seen several developers that want and have no problem by using server-side code blocks in a View when they are working with the MVC pattern. But I think the server-side code block should be used only in some advanced and special occasions and instead use an Expression Language. By using a lot of server-side code block can make the View messy and the solution can be difficult to implement, form the perspective of code maintainability and extensibility. If we instead use tags similar to HTML/XML we can make the code blend into HTML in a nice way.

Take a look at the following code:

<% if (ViewData != null && ViewData.HasError) {%>
<% } %>

<% if (ViewData.ExceptionType == ExceptionType.Critical) %>
      <div class="criticalException">
          Critical Error: <%= ViewData.ExceptionMessage%>
          <% if (ViewData.InnerException != null) } %>
          <% } %>
<% else %>
     <div class="exception">
        Error message :<br/><%= ViewData.ExceptionMessage%>
<% } %>

The above code is only used to demonstrate how messy a View can be when we have a lot of server-side code blocks. This code will not be easy for a designer or web developer to maintain. If we instead use an Expression Language (EL) and JSTL (JSP Stamdard Tag Library) for JSP in ASP.Net the View can be written like this:

<c:if test="${ViewData!=null && ViewData.HasError}">

     <c:when test="${ExceptionType == ExceptionType.Critical}">
         <div class="criticalException">
            Critical Error: <c:out value="${ViewData.ExceptionMessage}"/>
            <c:out value="${ViewData.InnerException.Message}"/>
         <div class="exception">
            Error message :<br/><c:out value="${ViewData.ExceptionMessage}"/>

The best part of the ${variable} is that it can evaluate null for us, and also do the type casting, so we don’t need to write:

<% if (ViewData.InnerException != null) } %>
<% } %>



Instead we simply write:



The best part, we shouldn't event need to use the ViewData, instead directly write:


Here is an example where a property path (sub-properties) is used:


In some cases we need some more logic to test some conditions etc, something that can’t be placed inside of a Controller. This logic can instead of being a server-code block be capsulated into an own custom tag.

The problem with EL today is the lack of supports in tools, so we only get an error first at runt-time and some IDE don’t have support for easy handle the EL. To make it more powerful the tools need to handle it also. But I prefer this way instead of using server-side code block and I hope something similar will be added to the ASP.NET MVC Framework.

Nikhil wrote a post about using AJAX with the ASP.Net MVC Framework (only a prototype). He uses code like this:

<% RenderBeginAjaxForm(Url.Action("Add"),
                       new { Update="taskList, UpdateType="appendBottom
startAddTask", Completed="endAddTask" }); %>
   <input type="text" name="name" id="nameTextBox" />
<% Ajax.Watermark("nameTextBox",
                  new { watermarkText="[What do you need to do?]", watermarkCssClass="watermark"}); %>

   <input type="submit" name="addTask" value="Add Task" />
<% RenderEndForm(); %>

The RenderBeginAjaxForm will render a <form> element with an onClick and onSubmit attribute etc. The RenderEndForm will also add a </form> The Ajax.Watermark is a way to extend a HTML element with a WaterMarker. I think this code is kind of “messy”. I would like to see some tags instead for example:

<ajax:Form Action="Add" Update="takstList" UpdateType="appendBottom" Hightlight="true" ...>
          <ajax:waterMarkTextBox name="name" id="nameTextBox" markerText="[What do you need to do?]".../>

By using this solution, tags will be nicely blended into HTML and remove server-side code and make it easy for web developers (They are used to HTML element and attribute) to simple apply it and also maintain it. We can also easy see that we have a <form> and a </form>. This looks similar to Server controls today but this should be a more light-weight control, and the runat=”server” shouldn’t be used ;) This is similar to ViewComponent shipped with MonoRail (I think ;)), but I don’t like the declaration syntax MonoRail used. I prefer to use a HTML similar way to add components (custom tags) etc.

What kind of solution do you prefer?


  • Having worked both with ASP.NET and Rails for a while I can say that I love the conciseness of Rails tags. I personally don't like all those <c:out, <c:when, <c:otherwise and so on. I've, but this is obviously my personal opinion, no problem working with tags like "<% if", "<% else". Apart from that to me "<% if" etc. are much more elegant.

    Anyway I'm anxiously waiting for the ASP.NET MVC framework.


  • I'm not a big fan of TemplateView. From my experience, the people working on these apps need to understand whats going on client and server side. Any abstraction leaks too quickly.

    I prefer having the html generated in a more of a builder class, extracting out business and presentation logic where possible, and then either fed into render (standard request) or issued in a response from init (asynch requests). I've built in custom js to handle the asynch xmlhttprequest rather than use a 3rd party library, and encapsulated the whole mess in a user control. The view and control code aren't quite as decoupled as I'd like (which I think is just inherent when what you're writing eventually has to boil down to html), but its clean enough to follow, and should make for an easy rewrite with the MSFT MVC bits when they're released.

    I'd also like to say that I've really enjoyed your posts on the MVC.

  • It’s all about doing the right abstraction ;)
    When I worked with classic ASP (I refer to classis ASP because a View with an MVC pattern are implemented similar to a classic ASP page) where we put server-side code blocks into the View, most pages become huge and a lot of server-side block with conditions and logic, logic we couldn’t place into Controllers. During 1996 and until ASP.Net was released I build B2B applications etc and it took only a few weeks until we call the server-side code block "the hell of ASP", because it wasn’t easy to maintain or extend. This is my experience.
    The interesting thing is that the .Net Community and the JAVA community seem to have different opinions. For example the JAVA community don’t like the server-side code blocks because it makes the code harder to maintain and extend. I talked to a friend who is deeply involved within the JAVA Community and he told me that Expression Language is something they prefer before server-side code. He gave me the following texts when I asked him about some resources:
    "Part of the problem stems from a basic difference in how programmers and designers think. Most programmers are versed in a procedural programming paradigm. In procedural programming, it is the programmer's job to tell the computer how to accomplish each designated task, detailing each step of the procedure. Web page designers operate under a different paradigm. HTML is a declarative language. The Web page designer does not tell the computer how to lay out the page; rather, the designer tells the computer what is desired: a table, a paragraph, an ordered list, and so on. Web page designers are generally not skilled at procedural programming and are not versed in the procedural mindset. This is one reason, although not the only one, why many JSP practitioners discourage (or outright ban) the use of JSP scripting elements within presentation pages"
    "Page design should be a process of describing what you want, rather than how to do it. The partnership between the tag author and his or her client -- the Web page designer -- revolves around the author embedding the how into the tag, so that the client can simply be declarative. This does involve more work for the tag author at the tag library design stage, but the resulting language is far more clean, reusable, and maintainable. Declarative languages also tend to be more compact."
    "The unified expression language started out as the JavaServer Pages Standard Tag Library (JSTL), version 1.0 expression language, originally called SPEL (Simplest Possible Expression Language). True to its name, this expression language made life easier for page authors by providing a simple, easy-to-use way to access external data objects. For example, the expression ${} is used to look up the customer JavaBeans component and call the getName method to retrieve the value of the name property. This value is then rendered into the page.
    By using this expression language, page authors could drastically reduce the amount of scripting in their pages, resulting in greater productivity, easier maintenance, and a flatter learning curve in terms of page development. Over the years, the expression language has evolved to include more advanced functionality, while still maintaining its simplicity.
    Because of the popularity and success of the expression language in the community, the JSP 2.0 expert group included it in its specification while making it more flexible. With the integration of the expression language into JSP 2.0, not only could page authors use the expressions inside of standard tag attributes (as they could before), but they could also use them in template text as well as with custom tags. In addition, they could use functions created by a tag author to invoke static methods not supported by the current expression language."
    I have a respect for the JAVA Community because they are so far ahead than the .Net community overall, BUT it doesn’t&nbsp;mean they have the right solution and still there&nbsp;are no silver bullets ;)

  • More more and more comments please, this is the kind of discussion I looked forward to :)
    But isn’t it strange that the JAVA Community moved away from server-side code block as much as possible because they notice how difficult it’s to maintain and extend, and the .Net Community want to move away from tags and custom tags (can almost compare this with controls) to use server-side script code, just a thought ;)

  • I think it is cool that you can do this but i get a bit worried that if you abstract the code like this you not going to be able to debug very easily making it hard to get to the root of some problems.

    It is funny now that you meantion about the java community moving away from server side code block and .net framework moving away from tags.

    I will tell you why i think .net developers preffer server side code : the server controls for are pain to work with, you end up writting so much code on your code behind file to get them to do what you want, sometimes writting new controls all together just to get that bit o functionality that you need. So most of the time jsut being able to write on the markup yourself is a lot easier. now if mvc get shiped with a load of html controls like, treeview, gridview etc that are not the web form controls; with only the javascript for example the collapse and expand of treeview controls then most people will use just use them.any way enough or rambling about this.

    I aggree with Alex G on the "...Inline code looks messy because of the yellow highlights in" it is messy, if you have a big page with lots of this it can get extremely, visual busy you could go blind. if visual studio just highlighted the whole line with a neutral colour. it would be better.

    i hope this helps.

  • Certainly an interesting discussion - I love you last comment - the trend being in the opposite direction, and it concerns me as well. Agree with the different developer/designer perspective that needs to be accounted for when it comes to the view.

    I actually personally thought the repeated were distracting... and had a very similar discussion with a fellow dev on the team. Tried out different syntax coloring options, and not yet sure that did it for me. However, at the same time I am not sure changing procedural logic code statements into tags makes a fundamental difference, even for designers. Interestingly enough, we tried this very early in the ASP.NET 1.0 days - but choosing to implement control flow in xml didn't jive for too long.

    However, based on the comments (incl. yours) on my blog post, I actually prototyped a rendering component concept that can be declaratively specified, yet does not inherit from System.Web.UI.Control. I'll see if its ready enough to post today...

  • Interesting post. However, If you take a look at the code,
    <c:if <c:choose <c:when
    syntactically appears to be a declarative approach to programming, but a careful look shows that this is not the case. Using such tags is simply procedural code just represented in a declarative markup. The tag is not telling the 'what' in any different way that the '' is and the reason is becaus both are addressing the same problem which is presentation LOGIC. I prefer to use lightweight presentation logic, have a look at the page and be able to visualise what the final html output will be, rather than use server side abstractions and try guessing what eash of those tags might output. I prefer <input type="text" rather than <asp:TextBox for example. I see the later as a needless abstraction of the html code it will produce.

    So, back to the <c:if and <c:choose
    In my opinion having the HTML which is by definition declaritive markup being driven by a declarative Presentation logic engine only obfuscates what the output will be. I think HTML lends itself to a more imparative presentation logic engine and it remains clear and concise since what you see is what you get, expressing your intent clearly and leaving no assumptions as to what the final html might look like which is what abstractions do for us.

    as for the ${ } safe dereferencing it a great and powerful feature and i would like to see it in C# too. It is merely syntatic sugar

    This safe 'a la groovy' dereferencing operator would work in a way so that for example string desc = order.Product.Description;
    would evaluate to null when either order or product is null
    (maybe could implemented into C# like so: order?.Product?.Description;)

    Just some thoughts

  • I would question the benefits of having your logic blend in with presentation. It's clear as day that few designers will ever touch that code with dreamweaver or another wysiwig tool, so all you have is developers looking and working with it.

    Lets look at the language and framework that's gaining the most momentum today - Ruby on Rails. Templating engine in RoR relies on the same old tags, but they have added a ton of shortcuts to cut down on typing AND increase readability... here's an example: and java way

    <a href="/display/details.aspx?id=">

    No wonder it's cluttered... here's how you do this in rails, same thing

    Getting things done better and faster isn't really about what kind of brackets you use but rather how easily the person after you could figure out your code.

  • Alex G:
    I like your last sentence; I think we can rewrite it to Flower’s statement
    Any fool can write code that a computer can understand. Good programmers write code that humans can understand ;)
    What do you think about this:
    "Page design should be a process of describing what you want, rather than how to do it. The partnership between the tag author and his or her client -- the Web page designer -- revolves around the author embedding the how into the tag, so that the client can simply be declarative. This does involve more work for the tag author at the tag library design stage, but the resulting language is far more clean, reusable, and maintainable. Declarative languages also tend to be more compact."

  • @Fredrik N

    To be more complete, I think that quote lacks the definition of "tag", after all, could be considered a code tag. Hiding functionality is a good concept, however the extremities of this shouldn't be forgotten - hiding too much is counter productive and hiding too little is pointless (my .02).

    I think the core reason for these two completely opposite points of view is quite simple. Some people like shorter code (not in expense of legibility) and others prefer more uniform code. Obviously each group finds their code easier to read. I'm in general a slow reader, so shorter and more compact is my preference.

  • please dont miss understand us we are not here to change your mind, i agree that with careless serverside code blocks the view will get messy, it will be illegiable, classic asp all over again. I like tags (i was reading about expression tags and making your own just the other day, and i like it and i think we should not look at this as expression tags vesus serverside (some people may even misunderstand this as a jave v .net hehe) both got their use and i will use both, like you said some of it will make the code look better to read, other cases you will need to use the 'raw' way and code reuse and making components should always be practiced in class or not.

    so is this expression tag language going to ship with mvc?

  • dancoe:
    I don't know if Microsoft are going to implement something similar to JSTL (JSP Standrad Tag Library, for example &lt;c:if&gt;) and Expression Language (${order.rows[10].item.description}).

  • well expression support is there already right? in the msdn library there are examples on how to create your own expression tags, are these the same ones that one would be creating to work as you meantion above?


  • This is an interesting discussion, and has been something that has been a main issue for me surrounding MS MVC. One of the reasons I adopted ASP.NET as a platform was its ability to allow me to rapidly develop web apps without having to mess around with inline code blocks. Being able to use a server control, such as a Repeater, to render a repeating list of items without having to do has a huge appeal. I mean, who the hell wants to have to write some collection looping code inline? I would love to see some marriage of the good parts of classic ASP.NET with the expanded control that MS MVC gives a developer over routing and code separation.

    I'm not saying that server controls were perfect; obviously we all know they weren't. All I'm saying is: give me the TDD friendly, clean architecture coupled with a more robust way to render my data in my view.

    Is that too much to ask for?

  • I have to aggree, mvc sounds great, allows the tdd, seems clean architecture wise but we will need some way to build this mvc controls.

  • Re: Steve Calvert

    You can still use Repeaters and DataLists (at least; I haven't tried any others yet) in MVC pages, using the CodeBehind to do the databinding.

  • IMO, much of this is just a visual illusion ;-)

    You say that the first snippet looks messy and that the other looks clean.

    Becuse of syntax highlight.

    The first snippet colors the code differently from the tags.
    And the second snippet makes the "code" look like the html

    The amount of actual code is pretty much the same.
    Its just a different syntax, and different colors.

    So, its an iluuuuuusssion..

  • Both points of view expressed here have their merits, but the use of 'custom tags', rather than 'inline server code' can be beneficial when used properly.

    Coming from a Java/JSP background, I have to admit being somewhat biased towards custom tags.

    One example of where custom tags improve the readability is when we're dealing with URL resolution - which of these looks neater and is quicker to type?

    <script src="" type="text/javascript"/>


    In the case of the custom tag, the URL resolution and the boilerplate 'type="text/javascript"' are dealt with by the server side code that implements the tag, leaving the markup not only cleaner, but more concise and self explanatory.

    What we effectively need is a version of the ASP.NET server-side controls that aren't reliant on postback, but are simply used to marshal data from the Model to the View (After all, this is usually the primary purpose of the markup)
    Think about something that provides the cleaner appearance of the server-side controls, with the power and convenience of the HTML helpers, and you're getting towards a more usable solution.

Comments have been disabled for this content.