Is Response.Write in ASP.NET views a bad idea? - asp.net-mvc

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 %> <%=?

Related

Does heavy use of methods within a view hinder caching?

I am experimenting with implementing BEM helpers in my Rails 4 app to help me write views more pleasantly.
Let's assume we have the following Haml view:
= block :user_bar, unregistered: current_user.unregistered? do |b|
- if current_user.unregistered?
= b.element :inner do
You are not registered.
Assuming the block and the fictional class BEMBlockBuilder with a method #element (of which an instance is passed as b) are defined, and assuming that current_user.unregistered? is true, we should get the following HTML output:
<div class="user-bar user-bar--unregistered">
<div class="user-bar__inner">
You are not registered.
</div>
</div>
This technique should make it possible to set up blocks, elements and apply modifiers to them without having to repeat the block's name every time, and it would make it possible able to apply modifiers simply based on the value bound to them being truthy.
The technique itself is somewhat similar to what happens when you use the form_for helper, in that it passes an instance of FormBuilder to the block.
The primary difference between this technique and the form_for helper is that you may end up using a multitude of nested blocks to render a view, of which the output might not be known.
Would this technique affect Rails's (or HAML's) ability to perform caching in a negative way, or would it damage rendering performance in general?
No, the implementation you are suggesting does not negatively impact caching - This includes page caching, action caching as well as Russian doll caching.
While the cases for page caching or action caching are fairly obvious, the reason Russian doll caching is also unaffected by custom view builders is because if the cache_key of model does not change - the block passed to the cache helper does not get re-evaluated irrespective of the view builder that is getting invoked underneath.
The above assumes that you avoid implicit state in your builder. Alex has already highlighted the importance of predictability in the comments.
Apart from that the only key issue is that streaming of templates will be tricky to handle. If that is not relevant to your use case, then you are good to go. In particular, if you are using HAML then you can not use streaming anyways. You may however consider exploring the thread for some interesting ideas on handling streaming templates.
If you want to avoid this issue, you may consider using small helper functions just to generate the class names according to BEM. Then you can use something like:
<div class="<%= bem_class(block: 'user-bar', el: 'inner', mods: ['unregistered']) %>">
</div>
This is obviously more verbose, but also easily allows you to handle cases where multiple blocks are applied to same DOM element, which is valid in BEM.
Finally, here are some key takeaways from an extremely well written article by Justin Weiss on view rendering performance assessment:
Sacrificing maintainability for marginal gains in performance is rarely a good solution
Complex logic does not belong in the views
Profiling tools are your friend.

Does Razor syntax provide a compelling advantage in UI markup?

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.

should I always use <%: instead of <%=

I know that <%: does the html.encode thing, but there are lots of situations when I'm sure that I don't need to encode, so why should I waste time on encoding stuff that I'm 100% sure it doesn't require to be encoded like for example <%:Url.Action("Index") %> or <%: Model.Id %> (is of type int)?
The : code nugget is part of the ASP.NET 4.0 web compiler and doesn't just call Html.Encode(). It works out whether or not the string is already encoded first (if the expression returns an IHtmlString then it probably won't get encoded).
This means it is safe to use it when inserting actual data or when inserting HTML from some type of helper method (if you write your own helper methods, they should always return IHtmlString as of MVC 2).
With regards to whether or not you always use it, of course you don't. But I'd rather not think about it too much and will be happier knowing I've gone some way towards fending off XSS attacks with little effort; therefore, I nearly always use it.
It also encourages you to make sure you return a MvcHtmlString from your HTML helper methods rather than a string.
One example where you would not want to use <%: is for strings that come from your resource file that include HTML escape characters. I don't think you can make a blanket statement that you should always use <%:.
Personally I use it only for stuff that I know that needs to be encoded. No need to use it for integer types <%: Model.Id %> but that's just a personal preference.
<%: model %> is equivalent of <%= Html.Encode(model)%>
using <%: saves keystrokes and improves your productivity,
but sometimes you will have a need to do <%= (not to encode whatever you are displaying on your page)
One of the advantages of encoding to HTML is that it makes the pages W3C Valid according to corresponding datatype. So why validate the document in the first place?
For the answer to that please check, please check: http://validator.w3.org/docs/why.html
Briefly validating HTML saves a lot of time later in the development cycle and its a good practice.
Its easier, if you use only one type, and makes the code more clean.
also, you never know, who will change the code, and makes out of a simple "100 %" statement, a not so 100% statement :-)
Normally, in a web environment, the performance on such things are not an issue.
i would suggest to only use "<%:" as a team development guideline. just to be on the safe side.

Branching logic in an MVC view

I find myself writing a lot of code in my views that looks like the code below. In this case, I want to add some explanatory HTML for a novice, and different HTML for an expert user.
<% if (ViewData["novice"] != null ) { %>
some extra HTML for a novice
<% } else { %>
some HTML for an expert
<% } %>
This is presentation logic, so it makes sense that it is in a view vs the controller. However, it gets ugly really fast, especially when ReSharper wants to move all the braces around to make it even uglier (is there a way to turn that off for views?).
My question is whether this is proper, or should I branch in the controller to two separate views? If I do two views, I will have a lot of duplicated HTML to maintain.
Or should I do two separate views with a shared partial view of the stuff that is in common?
Ideally, this kind of logic would be handled in the view model and the view should just be rendering the model.
So you might have something like in your view:
<%= ViewData["helptext"] %>
and your logic in the controller would be something like:
ViewData["helpText"] = isNovice ? noviceText : expertText;
that way you can push that logic back to the controller and keep your views nice and clean
You're trying to create 2 completely separate html pages with identical models. You want a separate view. Don't try to out clever the design pattern with conditional-branching logic.
HTML helpers aren't going to help you much here, since it appears you will not be repeating much logic other than if else.

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.

Resources