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) } %>
             <%=ViewData.InnerException.Message%>
          <% } %>
     </div>
<% else %>
     <div class="exception">
        Error message :<br/><%= ViewData.ExceptionMessage%>
     </div>
<% } %>

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:if>

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

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) } %>
        <%=ViewData.InnerException.Message%>
<% } %>

or:

<%=ViewData.CustomerID.ToString()%>
 

Instead we simply write:

${ViewData.InnerException.Message}

${ViewData.CustomerID} 

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

${CustomerID} 

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

${Order.Rows[1].Item.Price} 

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
",
                             Highlight="
True
",
                             Starting="
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?]".../>
</ajax:form>

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?

Published Tuesday, November 27, 2007 11:52 AM by Fredrik N
Filed under: ,

Comments

# re: MVC - Expression Language and custom tags

Tuesday, November 27, 2007 9:05 AM by Roberto gattinoni

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.

Regards,

Roberto.

# re: MVC - Expression Language and custom tags

Tuesday, November 27, 2007 9:22 AM by David Fauber

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.  

# re: MVC - Expression Language and custom tags

Tuesday, November 27, 2007 10:08 AM by Fredrik N

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 ${customer.name} 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 mean they have the right solution and still there are no silver bullets ;)

# re: MVC - Expression Language and custom tags

Tuesday, November 27, 2007 10:24 AM by Alex G

I think this is hardly optimizing anything, and in case of <c:out/> it's about twice as much typing required, so that's going backwards in my opinion.

I honestly don't see why replacing closing bracket with a closing tag would suddenly make it easier to maintain. Inline code looks messy because of the yellow highlights in vs.net. Make it on white, and you will barely notice it... but would that be a good thing?

To me, "optimizing" and "making it easier" means less typing and more clarity. There's a reason why coldfusion isn't popular - few like writing logic code with tags.

Check out http://www.stringtemplate.org/ - this in my opinion is a step forward.

# re: MVC - Expression Language and custom tags

Tuesday, November 27, 2007 10:33 AM by Fredrik N

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 ;)

# re: MVC - Expression Language and custom tags

Tuesday, November 27, 2007 12:32 PM by dancoe

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 asp.net 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 vs.net." 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.

# re: MVC - Expression Language and custom tags

Tuesday, November 27, 2007 12:33 PM by Nikhil Kothari

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...

# re: MVC - Expression Language and custom tags

Tuesday, November 27, 2007 2:00 PM by Fredrik N

One important thing here is that the custom tags (if we focus on that one for a moment), is something we developers can create. In this case we will own the code. If other has created custom tags which we can use, well it’s up to us if we want to use it. I have educated several developers which want to learn how to create a web based apps. Last week I had some people in my class which have created their own “components” to render some basic HTML elements to avoid too much server-side code, and also use the “components” for reusability. I have created several controls to make stuff easier and also to reuse code. I did some refactoring of the code in my Views, which I think is an important thing to do, to remove some code smell and make the Views easier to maintain. Well, to the point. Developers today create controls to make sure to do rendering easier and to reuse code etc, it’s nothing they do because they have to they choose to do it. I know that developers will do it in the future and are going to do it, I’m one of them. This is where the custom tags come in.

About the Expression Language vs Server-side code blocks, is it that the .Net Community have worked with server controls for a long time and have struggle for a long time to get something rendering the way they want, and that make them “hate” everything that looks like a tag; and now want more control, or is it the lack of the long experience that the JAVA Community have when it comes to build enterprise apps? They have used a MVC pattern for a long time, and also struggle with the server-side code blocks, while we struggle with the server controls (or some of us even server-side blocks within classic ASP). So based on their long experience about working with server-side code blocks in Views, have made them discover things that most of the .Net Community haven’t because they have not the same experience, just a thought.

I think it will be difficult to make me change my mind about Expression Language and the use of server-side code blocks. I still think the Views will get messy and hard to maintain when it has server-side code blocks where we need sometime put code to check for nulls etc. But the beauty is in the eye of the beholder, and how knows, maybe someone can change my mind, but I doubt that ;)

# re: MVC - Expression Language and custom tags

Tuesday, November 27, 2007 2:51 PM by Anastasiosyal

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 <c:if ..> is not telling the 'what' in any different way that the '<%if .. %>' 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

# re: MVC - Expression Language and custom tags

Tuesday, November 27, 2007 2:58 PM by Alex G

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:

asp.net and java way

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

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

<%= link_to @product.name, @product %>

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.

# re: MVC - Expression Language and custom tags

Tuesday, November 27, 2007 3:07 PM by Fredrik N

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."

# re: MVC - Expression Language and custom tags

Tuesday, November 27, 2007 3:32 PM by Alex G

@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.

# re: MVC - Expression Language and custom tags

Tuesday, November 27, 2007 6:00 PM by dancoe

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?

# re: MVC - Expression Language and custom tags

Wednesday, November 28, 2007 12:14 AM by Fredrik N

dancoe:

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

# Link Listing - November 27, 2007

Wednesday, November 28, 2007 12:25 AM by Christopher Steen

Link Listing - November 27, 2007

# Link Listing - November 27, 2007

Wednesday, November 28, 2007 12:26 AM by Christopher Steen

ASP.NET MVC - Expression Language and custom tags [Via: Fredrik N ] Are you excited about ASP.NET MVC?...

# re: MVC - Expression Language and custom tags

Wednesday, November 28, 2007 8:27 AM by dancoe

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?

------------

http://undocnet.blogspot.com

# re: MVC - Expression Language and custom tags

Thursday, November 29, 2007 11:27 AM by Steve Calvert

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 <% foreach(blah in blahList){ %> 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?

# re: MVC - Expression Language and custom tags

Thursday, November 29, 2007 4:44 PM by dancoe

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: MVC - Expression Language and custom tags

Thursday, November 29, 2007 9:26 PM by Bill Xie

Lots of server side code definitely mess up MVC views. Tags approach can not resolve this issue either. Server control plus databinding server code could be the right solution. This will nicely divide the view into two parts: visual and logic. When you examine the view markup code, you will not be bothered with the understanding of complex server codes. On the other hand, all data flushed to the view can be considered as the state of the view. The logic that controls how view is generated can be simply thought of as a state machine. Thus, things become much cleaner.

# MVC - Expression Language and custom tags

Friday, December 28, 2007 3:08 PM by Community Blogs

MVC - Expression Language and custom tags

# re: MVC - Expression Language and custom tags

Sunday, December 30, 2007 12:40 PM by Keith

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.

# re: MVC - Expression Language and custom tags

Friday, January 11, 2008 4:38 AM by Roger Alsing

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

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

Why?

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..

Leave a Comment

(required) 
(required) 
(optional)
(required)