views:

75

answers:

3

I have been trying to avoid using Response.Write(...) directly in my MVC Views. The reason being that I just need to type the string literals and the view engine knows what to do. However, in certain circumstances I seem to be creating way too many pointy brackets (<% %>). So, which of these 2 code snippets do you find more acceptable?

<% if (true)
{
  Response.Write(Model.SomeValue);
} %>

Or

<% if (true) { %>
<%= Model.SomeValue %>
<% } %>
+4  A: 

This is why Html Helpers exist (to avoid spaghetti code as much as possible):

<%= Html.MySuperHelper(Model.SomeValue) %>

Every time you need write an if statement in a view you might ask yourself the question: wouldn't it be better to write a helper method (which as a bonus could be unit tested) instead?

Darin Dimitrov
+2  A: 

How about a third possibility?

<%= condition ? Html.Encode(Model.SomeValue) : "" %>

Although in practice you should keep all but the very simplest logic out of your view altogether. Either do the work in your controller or wrap the logic up in a HTML helper of some kind.

LukeH
I'd use `Html.Encode( Model.SomeValue )`, if the property is not a value type.
tvanfosson
A: 

Or a fourth:

<%= condition ? Html.Encode(Model.SomeValue) : "" %>

gridzbi