Update: Later I found a cleaner and simple approach to do the same – read this post ASP.Net MVC – Conditional rendering Partial Views with Action<T> delegate
Following my previous post about Conditional Rendering, one of my colleague asked me how to render the partial view based on a condition.
Normal way of doing this is
1 | <% if(this.Model.Exists) |
I am not sure about any other technique for rendering partial view conditionally other than this (correct me if I am wrong :) ).
Then I thought about copying the pattern I have used in my previous post and came up with this code which could conditionally render partial views and you could use the Html extension like below, which more clean than the previous
<% Html.PartialIf(this.Model.Exists, "MyPartialView"); %>
Below is the Html extension I have created
1 | public static void PartialIf(this HtmlHelper htmlHelper, bool condition, string viewName) |
And here is the helper method I have used in the about extension ( most of the code snippet is taken from the MVC method Html.Renderpartial(…)
, thanks to open source )
1 | internal static IView FindPartialView(ViewContext viewContext, string partialViewName, ViewEngineCollection viewEngineCollection) |
Hope this helps