views:

47

answers:

5

Hi,

I'm trying to find out if there is a shorter way of writing data to a view than what I am currently doing. This is what I currently have in my view:

<td>
   <%
      if (Model.AnnualIncome != null)
      {
         %>
         <%: "R " + Model.AnnualIncome.ToString() %>
         <%
       }
   %>
</td>

Is there a shorter way of displaying annual income to the screen than having all the <% %>?

Thanks

+1  A: 

Something like <%=string.Format("R {0}", Model.AnnualIncome) %> should be more concise.

Edit: Oops, just realized that you don't want to print the "R" if it's null. In that case, something like this:

<%=(Model.AnnualIncome == null ? "" : string.Format("R {0}", Model.AnnualIncome)) %>
Paul
this can be further abbreviated to: <%=(Model.AnnualIncome ?? string.Format("R {0}", Model.AnnualIncome)) %>
jim
@jim, actually that will print just AnnualIncome without the "R" if it's not null, and print "R " if it is null.
Paul
paul - good catch. my fingers were desperate to add something by the looks of things :)
jim
+1  A: 

You could use another View Engine if you dont like <% %> everywhere.

Razor (CSHTML) isn't released yet but you can download a preview of it. I know there is also NHaml and another one as well.

Dismissile
+1  A: 

The MVC team are working on a new ViewEngine called Razor, that would allow nicer syntax:

http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx

Yakimych
Cool I will check it out. Thanks.
Brendan Vogt
+2  A: 

Does this work?

<td>
     <%: Model.AnnualIncome != null ? "R " + Model.AnnualIncome : string.Empty %>

</td>
Martin
Yes it does thanks.
Brendan Vogt
+2  A: 

How about using the ViewModel to format the data for the view?

public class AccountViewModel
{
    public decimal AnnualIncome { get; set; } 

    public string GetAnnualIncome()
    {
        return Model.AnnualIncome != null ? "R" + AnnualIncome : string.Empty;
    }
}

Then in your view, you can do something like:

<td><%= Model.GetAnnualIncome() %></td> 
metallic