tags:

views:

76

answers:

3

This is likely a very simple question with a straightforward answer but I'm something of a newbie when it comes to ASP.NET (MVC).

I am returning an address (in pieces) from my model. Some of components are null. Is there a simple or fluent-like way to check for that null value without a lot of extra code to determine whether or not to display the associated surrounding HTML (not just the value)?

Example:

<% foreach (var item in Model)
   { %>

    <h3>
        <%= Html.ActionLink(item.name, "Details", new { id = item.ID})%></h3>
    <div>
        <%= Html.Encode(item.address) %><br />
        <%= Html.Encode(item.city) %>,
        <%= Html.Encode(item.state) %>
        <%= Html.Encode(item.zip) %>
    </div>
<% } %>

In the above example, if there is a null value for item.address, I want the <br/> tag to be hidden as well so that only the city, state zip string is displayed.

I'm looking for something more elegant than just putting a <% if () { %> conditional out there. Thanks.

+3  A: 

You could write an extension method for HtmlHelper that checked to see if it was null or not, and would output nothing if it was, or field + <br /> if it wasn't.

public static string FieldLine(this HtmlHelper helper, object value, bool addBr) 
{
    if (value == null)
    {
        return string.Empty;
    }
    else if (addBr)
    {
        return helper.Encode(value) + "<br />";
    }
    else
    {
        return helper.Encode(value);
    }
}

Remember to import the namespace of your extension class into your View aspx. For this example, if my namespace was "MvcApplication1.Extensions", I would use

<%@ Import Namespace="MvcApplication1.Extensions" %>

at the top of my View. Then to use it, it would simply be:

<%= Html.FieldLine(item.address, true) %>
<%= Html.FieldLine(item.city, true) %>

etc.

womp
A: 

Assuming item.address is a string...

<%= Html.Encode(item.address) %>
<% if (!string.IsNullOrEmpty(item.address)) { %>
<br />
<% } %>

of course, this is typed out in the little comment box, so be wary of spelling, case, etc, etc.

datacop
+2  A: 

I'm adding another answer based on what womp described above.. I'd make the helper a bit more generic than he did, and still honor the origional Encode as well...

public static string EncodeWithHtml(this HtmlHelper helper, object value, string html) 
{
   if (value == null)
   {
      return string.Empty;
   }
   else
   {
      return helper.Encode(value) + html;
   }
}

This would allow you to do something like:

<%= Html.EncodeWithHtml(item.address, "<br />") %>

or

<%= Html.EncodeWithHtml(item.address, "<img src=\"images\home.gif\"><br />") %>
datacop
Sorry @datacop. Really wanted to give you the answer click, but @womp had some implementation guidance as well. Although I do like your more generic approach. Thanks!
Jay Stevens
No worries at all... his was first :) I just wanted to expand on what he offered a bit :)
datacop