8

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

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

forgive my ignorance if this isn't the case, this is just a guess: could you use an empty-string "" instead of "N/A" for the NullDisplayText, and put the label inside the DataFormatString (such as "Balance: {0:c}") and and achieve what the O.P. is asking for?
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.