Sharing my knowledge

ASP.Net MVC – Conditional rendering Partial Views with Action<T> delegate

This is an update to my previous post regarding conditional rendering partial views, in that I used the internal implementation of the Html.RenderPartail(…) method to create the Html extension. Later I found a simple way to achieve the same using Action<T> delegate

<p>Partial rendering with Action Methods</p>        
<% Html.PartialIf(this.Model.Exists, html => html.RenderPartial("MyPartialView")); %>

If you look at the “PartialIf” implementation, it is simple, cleaner than the previous technique I have mentioned in my post.

public static void PartialIf(this HtmlHelper htmlHelper, bool condition, Action<HtmlHelper> action)
    if (condition)

That’s it :)

ASP.Net MVC - Conditional Rendering

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