Does Razor syntax provide a compelling advantage in UI markup? - asp.net-mvc

I notice Scott Guthrie is starting to mention Razor a fair bit on his blog but I'm just not that sure that it's a good fit for my style.
Granted it's a fairly unfamiliar style for someone who's pretty used to a "standard" sort of ASP.Net markup (content place holders and inline code), but it just feels like a lot of additional pages to manage and less clear markup to me.
What are other peoples' feelings on it? Is it something that you believe should be seriously considered when scaffolding new MVC pages or is it just trying to solve a problem that doesn't exist?

[Disclaimer: I'm one of the Microsoft developers on MVC and Razor, so I might be a bit biased :)]
We designed Razor to be a concise templating language that uses only the minimal necessary amount of control characters. I would say that large parts of your views can be expressed with fewer characters than the same code using the "traditional" WebForms syntax.
For example the following code snippet in ASPX syntax:
<% if(someCondition) { %>
<ol>
<% foreach(var item in Model) { %>
<li><%: item.ToString() %></li>
<% } %>
</ol>
<% } %>
Can be expressed as follows in Razor:
#if(someCondition) {
<ol>
#foreach(var item in Model) {
<li>#item.ToString()</li>
}
</ol>
}
While the ASPX version has 21 transition characters (the <% and %>), the Razor version has only three (#)
I would say that the advantages of Razor are as follows:
Concise syntax, which is very similar to the way you write regular C# code (check out the following recent blog post by Phil Haack comparing Asxp with Razor syntax: http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx)
Automatic HTML encoding of output (which helps protect you from html injection attacks)
Built in (though not 100%) validation of your markup which helps you avoid unbalanced tags
The page-related concepts also map easily from what you have in ASPX
As you can see inline code is still allowed
Sections (which can be optional) are equivalent to content placeholders
Layout pages instead of Master pages
The concepts of full and partial views are the same
#functions { ... } blocks instead of <script runat="server"> ... </script>
In addition Razor has a number of useful concepts that I would say are better than what is available in ASPX:
#helper functions for really easy creation of functions that emit markup
#model keyword for specifying your view's model type without having to write a <%# Page ... directive with the full class name
I would like to think that we have tackled a real problem, which is to allow you to more easily write concise and standards-compliant views while at the same time providing you with ways to refactor common code.
Of course, not everyone will prefer the syntax which is why we are also fully supporting the ASPX view engine. In addition you can check out Spark and NHaml, which are two 3rd-party view engines that enjoy significant community following. The following blog post has a good comparison of the different offerings: Link

Personally I really appreciate the reduction in how many escape characters are used. Using <% %> gets very tedious when compared to #{} and is not nearly as syntactically appealing.
Moreover, writing a whole definition for the codebehind and page is simplified to a single #model model.
As also noted by marcind, not having to always include runat=server is very nice also.
Overall, I really appreciate using the Razor engine and find it not only makes things easier on me to develop but also makes code easier to read.

Related

ASP.NET MVC AJAX actionlink injects onclick attribute

I have a partial view which outputs a list of editors. Each editor in the list has a delete link, which is called using #Ajax.actionlink, like this:
if(Model.Any()){
<ul>
#foreach (var editor in Model)
{
<li>#editor.firstName #editor.lastName, #editor.emailAddress (#Ajax.ActionLink("Delete", "DeleteEditor", "EditorSurface", new { editorId = editor.id }, new AjaxOptions()))</li>
}
</ul>
}
I've included #using System.Web.Optimization; in my view and am calling the jquery unobtrusive ajax script from my view too:
#Scripts.Render("~/scripts/jquery.unobtrusive-ajax.min.js")
The issue is that when I view source, the rendered mark-up for my editor list items is like this:
<li>John Smith, johnsmith#example.com (Delete)</li>
I was a little disappointed to see the inline JavaScript in the delete links and was hoping for something a little 'cleaner' (possibly data attributes or something?). It strikes me this is going to be difficult to hook into (to provide confirmation messages etc).
Question is, is this the expected output of AJAX in ASP.NET MVC? I'm very new to this so not sure if I'm doing something wrong in my implementation.
Many thanks.
Yes, this is the markup the Ajax.* family of helpers produces. My recommendation in general, and especially in light of the fact that you don't want the on* attributes added, is to avoid these helpers like the plague. You'll have much cleaner and maintainable (though slightly more verbose) code handling AJAX yourself, i.e. just add a standard Html.ActionLink and then use jQuery to attach an event handler that calls the AJAX. Plus, when something goes wrong, as it almost inevitably does, you have full knowledge and control over the JavaScript that is running, rather than being at the mercy of some opinionated Microsoft dev.

Going from Webforms to MVC 4

So I'm converting a WebForms application into ASP.NET MVC 4 and I would like to make sure that I'm making correct coding choices and assumptions.
1). Is the MVC equivalent of a user control a partial view?
2). In an aspx page you have a control like
<asp:Label id="X" runat="server">
with the following code in the code behind:
X.Visible = some_condition ? true : false;
Ok so, for MVC is this code equivalent?
View:
<label id="X" style="display: #Model.IsViewable">
Model:
IsViewable = some_condition ? "inline-block" : "none";
1.) Well, kinda, sorta, but no not really. Very different things - a detailed explanation would be lengthy.
2.) Equivalent maybe, but not really a good thing to do. Your model should contain data only. But yes, you can use this data in your razor views to conditionally do things including show or not show things. However, putting the css strings straight into your model data is klunky at best as well as it's usually a good idea to avoid inline styles whenever possible. IsViewable as a boolean would be better, and you can still handle showing or hiding elements (in a different way).

Looking for repeater type functionality in ASP.Net MVC

I am used to using a Repeater control in conventional ASP.Net web projects. I see ASP.Net MVC doesn't have this sort of thing. What should I be using here?
EDIT:
In response to the question, what am I trying to do that I can't achieve in the foreach. I guess I am trying to get a alternating row style. Also, it just feels somewhat wrong to have stuff other than markup in the view. But maybe I will get over that as I work with it. Thanks for the answers.
The simplest thing to use is a foreach loop.
What are you trying to do?
EDIT:
<% bool odd = false;
foreach(var row in something) { %>
<tr class="<%= odd ? "OddRow" : "EvenRow" %>">
...
</tr>
<% odd = !odd; } %>
To add to SLaks response.
You could encapsulate your html into a Partial View.
Call <%= Html.Partial("ViewName", optional_ViewModel) %>.
This might feel closer to the repeater control. Where the PartialView would be sort of like your item template.
This approach also lends itself to code reuse very nicely.
If you miss a lot of the features of WebForms, maybe you just need a richer view engine? Might I suggest the Spark View Engine? Like WebForms, there's lots of functionality included so you don't have to keep rewriting the same stuff and/or write a bunch of your own helpers.
alternating row style can be achieved by css styles ... BTW - each one funcionality from web forms can be achieved in mvc ... in the end all is html, js and css
You could even create an HTML helper for this.

Correct coding convention for embedded code on web page templates

I had come experience with PHP a time ago and now I'm learning to use Ruby on Rails. But one simple question bothered me in both these languages, so I think I can cross-post it to both tags.
As you know, one of the concepts there is that one can embed PHP or Ruby code into web page template. Then these statements are executed and result of its execution is inserted in certain places of the page, marked with "brackets" <%= ... %>.
Or... wait. We program Ruby/PHP, but not HTML. Maybe we should treat template as Ruby/PHP code, into which sometimes HTML markup is inserted? So the process is treated like that HTML are inserted into ruby code into the "brackets" %> ... <%.
These are two different approaches:
HTML page is the primary entity, and it is affected by code execution; or
code is the primary entity, and it is executed, while HTML snippets are inserted in certain places.
This philosophy leads to different possibilities in coding conventions: result of code execution influences the page If we adhere the first insight, then the code would look like this:
<p>
<% (1..10).foreach do |i| %>
Iteration number <strong><%= i %></strong>. <br/>
<% end %>
</p>
But if we stick to the second alternative, the code would be formatted like this:
<%
%><p><%
(1..10).foreach do |i|
%>Iteration number <strong><%
%><%= i %><%
%></strong>. <br/><%
end
%>
How should the concept of templates be construed? What concepts do you, way more experienced Web developers, account for the coding convention?
If this is in your View layer (and it should be), then the HTML is the primary entity. It's the most pertinent part of that layer -- marking up your data to display in meaningful ways to the user.
Even aside from that, your second example is nearly unreadable. I see what you're doing, but it took me a minute to wrap my brain around it. I've also never, ever seen View-layer code like your second example (and I would make it one of my priorities to change it wherever I saw it if it was in a project I was working on).
To be more concise: you're putting the emphasis on the wrong thing. In my opinion, readability trumps just about everything else. The coding style that produces the most readable code is therefore the most superior (ceteris paribus and YMMV, of course).
Maybe you should look into Haml? I don't know if there's a php equivalent, but as far as Rails goes, it's somewhere in between the two schemes. It's not quite code centric. But when used right, all the raw html is prepared programatically.
In short everything is considered text to be directly outputted, unless prefixed with either a %, - or =. Which translate to html-tag, ruby code that doesn't output. Ruby code that does output. Haml then uses whitespacing to nest things properly, much like python does. Raw html outputs untouched but using % to specify a tag handles closing tags.
Sample:
#outer-div
- #items.each do |i|
%span.item
= i
%br
Outputs
<div id="outer-div">
<span class="item">
item
</span>
<br>
</div>
See the haml tutorial for more information.
To answer the central question. The bulk of any page is going to be HTML or raw text. We reduce the bulk of that text with includes and helpers, but it's still there. If there were a truly code centered approach my use of it would depend on the ratio of program logic to html. Personally I'd rather go with the html centered approach.
If you are interested in a code-oriented view, this is something you might try implementing as a pure Ruby DSL:
tag :p, :class => 'iterations-container' do
(1..10).each do |i|
text "Iteration number "
tag :strong { text i }
text "."
tag :br
end
end
Or perhaps instead of tag :p do ... end, you may favor tag.p do ... end.
I recommend doing only very simple logic in your template files. That way designers who can edit HTML can easily edit even those files to alter the layout if need be.

Is Response.Write in ASP.NET views a bad idea?

Most of my company's web programming background is PHP, so ASP.NET MVC was a logical choice for our newest web application that also needed to work as a back-end to a separate Winforms app. However, we keep finding ourselves going down the road we typically followed in php - echoing lots of tags for conditional output. Is this a bad idea in ASP.NET MVC?
For example, without Response.Write:
<%if (OurUserSession.IsMultiAccount)
{%>
<%=Html.ActionLink("SwitchAccount", "Accounts", "Login") %><span>|</span>
<%}%>
With Response.Write:
<%if (OurUserSession.IsMultiAccount)
Response.Write (Html.ActionLink("Swith Account", "Accounts", "Login") + "<span>|</span>");
%>
The difference is rather minor here, but sometimes our view logic gets more complex (very complex view logic, i.e. anything more than booleans, we just offload to the controller). The second seems easier to read, but I wanted to see if there were any thoughts on the matter.
As Mehrdad says, there is no backside of using Response.Write() compared to <%= %>. However, if you want to make your code even more readable, it may be possible with an extension method:
public static string WriteIf(this HtmlHelper helper, bool condition, string tag) {
return condition ? tag : "";
}
Which would be used like this:
<%= Html.WriteIf(UserSession.IsMultiAccount,
Html.ActionLink("Swith Account", "Accounts", "Login") + "<span>|</span>") %>
Which one is easier to read is, I guess, a matter of taste.
Nope. It's not a bad idea. Functionally, those snippets are equivalent. Go with the most readable in your specific case.
<%= is exactly shorthand for Response.Write - these two statements are not just functionally equivalent, they are identical.
The only difference is readability and brevity, for which <%= is fine for anyone who's been in ASP for a little while. The important thing with R.Write in general is that you avoid writing string literal HTML with it because that's very subject to human error.
This question can be approached from 2 aspects:
Performance
Readability/Maintenance
1. Performance
Back in ASP classic days, every time you closed %> and re-opened <% there was some script processing cost (but processing power was equally limited). Having this in mind, if we are talking about a foreach loop with lots of elements I might be inclined to simply using Response.Write.
2. Readability
Rather than other opinions, I personally believe Response.Write is plenty readable. I think new-gen coders don't like it simply because it reminds them of the classic version.
I do however like verymuch -Tomas Lycken-'s answer. Seems like the best of 2 worlds.
Everytime I code in any language I try not to stray far from Guido's Python's PEP-8 Styling guidelines , but it clashes sometimes with .net's C#'s ones.
After thoughts
Although that does raise a question:
Is it better to invoke a custom made method over %> <%=?

Resources