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

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))%>                         <% } %> 

ASP.NET Exception Handling in background threads


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.

How do you update the aspnetdb membership IsApproved value?
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..
Restrict file types allowed for upload
[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..
MVC & EF - using
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..
Style list of divs as 2 column layout with css

MVC2 DataAnnotations on ViewModel - Don't understand using it with MVVM pattern

Creating a 'website builder' - How would I architect it?


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)) %> 

65 out of 100 based on 50 user ratings 775 reviews