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
1 | <% if (this.Model.Exists) { %> |
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
1 | public static string If(this HtmlHelper htmlHelper, bool condition, Func<HtmlHelper, string> action) |
What about IfElse condition, we could write another helper method for that
1 | public static string IfElse(this HtmlHelper htmlHelper, bool condition, Func<HtmlHelper, string> trueAction, Func<HtmlHelper, string> falseAction) |
Ok, now we got a conditionally rendered element, sometimes we may have to put a wrapper around this element. So I have written another Html helper method which will help you to put any html element around a particular element.
1 | public static string HtmlTag(this HtmlHelper htmlHelper, HtmlTextWriterTag tag, object htmlAttributes, Func<HtmlHelper, string> action) |
An overloaded version which doesn’t accept HtmlAttributes
as parameter
1 | public static string HtmlTag(this HtmlHelper htmlHelper, HtmlTextWriterTag tag, Func<HtmlHelper, string> action) |
Below are some examples of using these helpers.
1 | <%= Html.HtmlTag(HtmlTextWriterTag.Div, action => action.ActionLink("Without attributes","About") ) %> |
Hope this will help you.