ASP.Net MVC - Conditional Rendering
Posted on: 03 Jan 2010
| Filed under: CodeProject, MVC
| Tagged under: ASP.NET, CodeProject, MVC
|
No comments yet
We come across situations like rendering elements based on the conditions in Model. For example, in the view if we want to show a TextBox if some property is true. A normal way of doing this is like below
<% if (this.Model.Exists)
{%>
<%= Html.TextBox("Test") %>
<% }
This looks like old classic asp style, and when it comes to code maintenance this will be a pain. So a clean way is to use an Html helper to generate this
<%= Html.If(this.Model.Exists, action => action.TextBox("Name")) %>
which looks cleaner than the old one. Source code for this helper method is
public static string If(this HtmlHelper htmlHelper, bool condition, Func<HtmlHelper, string> action)
{
if (condition)
{
return action.Invoke(htmlHelper);
}
return string.Empty;
}
What about IfElse condition, we could write another helper method for that
Read more...