Click here to Skip to main content
Licence CPOL
First Posted 1 Feb 2010
Views 9,191
Bookmarked 10 times

ASP.NET MVC – Conditional Rendering

By | 3 Feb 2010 | Technical Blog
How we could write a conditional rendering HTML helper in ASP.NET MVC
A Technical Blog article. View original blog here.[^]

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. The 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:

public static string IfElse(this HtmlHelper htmlHelper, bool condition, Func<HtmlHelper, 
	string> trueAction, Func<HtmlHelper, string> falseAction)
{
    if (condition)
    {
        return trueAction.Invoke(htmlHelper);
    }

    return falseAction.Invoke(htmlHelper);
}

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.

public static string HtmlTag(this HtmlHelper htmlHelper, HtmlTextWriterTag tag, 
	object htmlAttributes, Func<HtmlHelper, string> action)
{
    var attributes = new RouteValueDictionary(htmlAttributes);

    using (var sw = new StringWriter())
    {
        using (var htmlWriter = new HtmlTextWriter(sw))
        {
            // Add attributes
            foreach (var attribute in attributes)
            {
                htmlWriter.AddAttribute(attribute.Key, attribute.Value != null ? 
			attribute.Value.ToString() : string.Empty);
            }

            htmlWriter.RenderBeginTag(tag);
            htmlWriter.Write(action.Invoke(htmlHelper));
            htmlWriter.RenderEndTag();
        }

        return sw.ToString();
    }

    return string.Empty;
}

An overloaded version which doesn't accept HtmlAttributes as parameter:

public static string HtmlTag(this HtmlHelper htmlHelper, 
	HtmlTextWriterTag tag, Func<HtmlHelper, string> action)
{
    return HtmlTag(htmlHelper, tag, null, action);
}

Below are some examples of using these helpers:

<%= Html.HtmlTag(HtmlTextWriterTag.Div, action => 
	action.ActionLink("Without attributes","About") ) %>

<%= Html.HtmlTag(HtmlTextWriterTag.Div, new { name = "wrapper", @class = "styleclass" }, 
	action => action.ActionLink("With Attributes", "About")) %>

<%= Html.HtmlTag(HtmlTextWriterTag.Div, null, action => action.ActionLink
	("Null attributes", "About")) %>

<%= Html.IfElse(this.Model.Exists, trueAction => trueAction.Encode("Sample"), 
	falseAction => falseAction.TextBox("SampleName")) %>

<%--
Nesting
<div>
   <span>
       <a href="/Home/About">About</a>
   </span>
</div>
--%>
<%= Html.If(this.Model.Exists,
    div => div.HtmlTag(HtmlTextWriterTag.Div,
        span => span.HtmlTag(HtmlTextWriterTag.Span,
anchor => anchor.ActionLink("About", "About"))
)) %>

Hope this will help you.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Rajeesh.C.V

Team Leader
Applied Development
India India

Member

Follow on Twitter Follow on Twitter
I am someone who is passionate about programming. I started my career with classic asp and VB 6, later dived into the world of .NET. My ambition is to become a technical architect who could design complex systems in a simplistic form which obeys the "Laws of nature"
 
My personal blog

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralForgot conditional (?) operator PinmemberOPerttilä5:32 14 Feb '10  
GeneralRe: Forgot conditional (?) operator PinmemberRajeesh.C.V5:57 14 Feb '10  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120517.1 | Last Updated 3 Feb 2010
Article Copyright 2010 by Rajeesh.C.V
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid