tags:

views:

102

answers:

3

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.

+2  A: 

Nope. It's not a bad idea. Functionally, those snippets are equivalent. Go with the most readable in your specific case.

Mehrdad Afshari
+3  A: 

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.

Tomas Lycken
Oh holy crap! I've never thought to use extensions for the aspx page like that... I'll have to look into that! I have quite a few blocks that are conditional!
Joshua
Again, this is just a matter of making things easier to read. If you have many (that is, *many*) conditions you use an extension method like this one on, there might be perf issues. But in that case I guess you'll notice... ;)
Tomas Lycken
Hey, that's a pretty useful extension method!
Jess
+2  A: 

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

annakata