Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 906
Beep beep Avatar asked Jan 24 '23 05:01

Beep beep


1 Answers

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.

like image 131
Tomas Aschan Avatar answered Jan 25 '23 19:01

Tomas Aschan