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() %>
<%
}
%&开发者_如何学Gogt;
</td>
Is there a shorter way of displaying annual income to the screen than having all the <% %>?
Thanks
Does this work?
<td>
<%: Model.AnnualIncome != null ? "R " + Model.AnnualIncome : string.Empty %>
</td>
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>
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)) %>
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.
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
精彩评论