Rajeeshcv.com

Sharing my knowledge

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

Posted on: 28 Jan 2010 | Filed under: .NET, ASP.NET, CodeProject, MVC | Tagged under: ASP.NET, CodeProject, HTML Extension, MVC | 1 comments

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)
    {
        action.Invoke(htmlHelper);
    }
}

That’s it :)

If you like this please share :

Comments

anand

anand

Commented one month ago

Hi Rajeesh,

I am new to MVC, could you tell me where do i utthe above code snippet, is it the global.asax. ?

Thanks


Leave your comments