Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean way to output values in ASP.NET MVC Views when value is not null

Is there a better way to write the code below? I have quite a few blocks that are similar, and this is making the code in the Viewpage very messy to work with.

The data value with the associated label only needs to be output when certain conditions are met, which is almost always if the value is not null.

The options I can think is to use a response.write to atleast minimize the usage of the ASP script tags, or to format the webpage is such a way that the label displays with an appropriate n/a type value.

<% if (myData.Balance != null)
{ %>                       
   Balance: <%= String.Format("{0:C}", (myData.Balance))%>                        
<% } %>
like image 265
Swoop Avatar asked May 21 '10 20:05

Swoop


2 Answers

If you make use of the DisplayFormatAttribute class in System.ComponentModel.DataAnnotations you can explicitly control the output of null values in your view without dealing with inline script tags. By itself that won't help you remove the labels tied to the value, but you can at least have it automatically substitute an output if the value is null.

[DisplayFormat(NullDisplayText = "N/A", DataFormatString = "{0:c}")]
public double? Price { get; set; }

<%=Html.DisplayFor(m => m.Price)%>

With the above code it will automatically display "N/A" if the value is null, otherwise it will display the value using the default currency format.

As an alternative, if you want to remove the label too and don't want to deal with script tags in your view you could make your own HtmlHelper which takes an expression in the same format of Html.DisplayFor(expression) and then returns the combined output of an Html.LabelFor(expression) and Html.DisplayFor(expression) if and only if the value mapped to that expression is not null.

like image 160
Nathan Taylor Avatar answered Oct 09 '22 14:10

Nathan Taylor


If you stick the "Balance" inside the format string, and use Response.Write, it ends up looking a lot cleaner, I think:

<% if (myData.Balance != null) 
       Response.Write(String.Format("Balance: {0:C}", myData.Balance)) %>
like image 20
tzaman Avatar answered Oct 09 '22 12:10

tzaman