should I always use <%: instead of <%= - asp.net-mvc

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.

Related

Best practice for Prevent XSS hacking

I am member of team with 25 developer.we use mvc.net application that security is a n important for us.we use #Html.AntiForgeryToken() and anything that related with security but We are concerned about Prevent XSS hacking.
we encode every where but some places we need html from user.
What is the best practice for Prevent XSS hacking?
The golden rule to prevent XSS is to HTML encode everything that you are outputting to a view.
Hopefully the # Razor function already does that automatically for you.
So when you write one of the following you are pretty safe:
#Model.SomeProperty
#Html.DisplayFor(x => x.SomeProperty)
You should be careful with the #Html.Raw helper:
#Html.Raw(Model.SomeProperty)
If you use that the output will not be HTML encoded. This doesn't mean that your site is vulnerable to XSS injection. For example if you have total control of the property and is not coming from an user input you should be pretty safe.
If you are using the WebForms view engine then you should be more careful because the <%= function doesn't HTML encode the output.
So the following is not safe:
<%= Model.SomeProperty %>
You should use one of the following:
<%= Html.DisplayFor(x => x.SomeProperty) %>
<%: Model.SomeProperty %>
If on the other hand you need to output some user input without HTML encoding it I would recommend you using the AntiXSS library from Microsoft. It will filter out all dangerous tags from the input and you are safe to output it. For example it will remove the <script> tags from the input. There's also an article on MSDN about this library that you might checkout.

Closer to the HTML...then why the HtmlHelper?

I often see, touted as one of the big benefits of ASP.NET MVC, the fact that it gets you closer to the actual page markup, as opposed to the pseudomarkup of WebForms.
If that's the case, then why does the HtmlHelper exist? It seems like all this LabelFor, TextBoxFor stuff is just as much pseudomarkup as <asp:Label> and <asp:TextBox> are in WebForms.
What am I missing? Why is there an HtmlHelper class? Do people use it in real life?
Whilst you are right in saying that HtmlHelper functions do abstract away the exact markup rendered, the big advantage of this is that the views are more DRY and you are able to pass in the necessary parameters to the functions in order to customise the HTML generated.
Rather than having to manually type out a full <input /> tag, complete with value=<%= Model.Property %>, Html.TextBoxFor is a more concise way of outputting the same thing. And as with all DRY approaches, if you need to change the HTML for all textboxes in your application (e.g. to output a new attribute) all you need to do is change the HtmlHelper method.
They seem to me a little like simple, lightweight partial views that are just designed to output some consistent HTML given some input.
The point of HTML helpers is to eliminate tedious and repetitive <input> tags.
Unlike server-side controls, HTML helpers emit raw, (fairly-)predictable HTML.
It simplifies the creation of those and allows them to be strongly named. Of course people use this!
I don't quite agree with the answers, and i somehow agree with you.
You can think of the helpers as pre-built custom controls, if you want to have some code generated you can make use of the helpers, if you want a clean approach and get closer to the html then don't.
The important point here is that MVC allows you to get close to the html, but does not limit you to only that.
You can create your own helper that created the markup you wish, and use that instead.
At the end of the day, it comes down to your own preference, and you can choose to or choose not to be closer to the html

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

Better way to implement an Html Helper method?

I created an html helper
Html.BreadCrumb(IDictionary<string, string> crumbs)
Where the first string is the label and the second string is the URL.
The helper creates the html required (an unordered list, some classes for first element, current element, last element, dead element and separators etc)
All working nice, but I do this by creating a stringbuilder, pumping all the html in it and returning the stringbuilder's content as a string.
I figure in this example it doesn't matter all that much, but what if an Html helper is churning out a big load of html? Isn't there a way to push it to Response.Write instead of a stringbuilder?
Or any other issues/improvements you have?
BTW we have a naming pattern in ASP.NET MVC for the various rendering techniques.
Helpers that return a string of what they are should be named what they are. For example, Url.Action() and Html.TextBox() return those exact items. Thus, these helpers should be used with the <%= %> syntax.
Helpers that render directly to the output stream should start with Render. For example, Html.RenderPartial(). These are used with the <% %> syntax.
Helpers that use the IDisposable pattern should be named with Begin/End. For example, Html.BeginForm() and Html.EndForm(). These should also be used with the <% %> syntax.
Thanks,
Eilon
It certainly is possible to use Response.Write instead of returning a string; see the source for System.Web.Mvc.Ajax.Form (in AjaxExtensions.cs) in the MVC source for an example.
You then call the helper with <% instead of <%=.
Will it be any faster? I doubt it, but it's easy to test.
I don't think you will have any performance problems as long as the size of the HTML pages you produce is reasonable. And when you really start to create pages of megabytes in size, then you should ask yourself, why are you creating such huge HTML files?

Why shouldn't Helpers have html in them?

I have heard that it's best not to actually have any html in your helpers; my question is, Why not? And furthermore, if you were trying to generate an html list or something like that, how can I avoid actual tags?
Thanks!
-fREW
My advice - if it's small pieces of HTML (a couple of tags) don't worry about it. More than that - think about partials (as pulling strings of html together in a helper is a pain that's what the views are good at).
I regularly include HTML in my helpers (either directly or through calls to Rails methods like link_to). My world has not come crashing down around me. In fact I'd to so far as to say my code is very clean, maintainable and understandable because of it.
Only last night I wrote a link_to_user helper to spits out html with normal link to the user along with the user's icon next to it. I could have done it in a partial, but I think link_to_user is a much cleaner way to handle it.
I don't see that there's anything wrong with it. The majority of the rails helpers generate HTML code (which is their purpose) - to me this implies that's what you're supposed to do yourself.
There is however the ever-present issue of code readability. If you have a helper which just builds a big string of raw HTML, then it's going to be hard to understand. While it's fine to generate HTML in helpers, you should do it using things like content_tag, and render :partial rather than just return %Q(<a href="#{something}">#{text}>)
This isn't a full answer to your question, but you can create html in your tags via the content_tag method. My guess as to why would be cleanliness of code.
Also, content_tag allows you to nest tags in blocks. Check out this blog post on content_tag.
On Rails 3 you can use *html_safe* String method to make your helper methods return html tags that won't be escaped.
As mentioned before, helpers are generally thought to be used as business logic, for doing something that drives view code, but is not view code itself. The most conventional place to put things that generate snippets of view code is a partial. Partials can call a helper if needed, but for the sake of keeping things separated, it's best to keep business in the helper and view in the partial.
Also, bear in mind this is all convention, not hard and fast rules. If there's a good reason to break the convention, do what works best.
I put html into partials usually.
Think about semantics. If you put html in a string, you lose the semantic aspect of it: it becomes a string instead of markup. Very different. For example, you cannot validate a string, but you can validate markup.
The reason I wanna put html in a helper instead of partial (and how I found this thread) is terseness. I would like to be able to write =hr instead of =render 'hr'.
To answer the question I didn't ask ;-) : to un-escape HTML in a helper, try this
def hr
raw '<hr />'
end

Resources