4

I have some Customer Details and I only want to show fields which have a value.

For example if Telephone is null don't show it.

I currently have in my view model

    public string FormattedTelephone
    {
        get { return string.IsNullOrEmpty(this.Telephone) ? " " : this.Telephone; }
    }

And in my view

@Html.DisplayFor(model => model.FormattedTelephone)

This is working correctly, however, I would like to show the Field Name if the field has a value e.g.

Telephone: 02890777654

If I use @Html.DisplayNameFor in my view it shows the field name even if the field is null.

I also want to style the field name in bold and unsure of where I style it - the view or the view model.

Sachin Kainth
  • 45,256
  • 81
  • 201
  • 304
Stephen
  • 803
  • 1
  • 11
  • 29

4 Answers4

5

For the bold style you can use this bit of code in your view, but of course it's proper to use an external style sheet.

<style type="text/css">
.telephone{
font-weight: bold;
}
</style>

You can do the check for null in your view and conditionally display the data:

 @if (Model.FomattedTelephone != null)
    {
       <div class="telephone">
          @Html.DisplayFor(model => model.FormattedTelephone)</div>
    }
Forty-Two
  • 7,535
  • 2
  • 37
  • 54
1

For style add a class for to the span you can put around field name.

You could create your own HtmlHelper that will only write if string is not null or empty.

Or you could add a DisplayTemplates something like here: How do I create a MVC Razor template for DisplayFor()

For more background on helpers in razor read the following http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx

And if they're in your App_Code folder read the answer to this Using MVC HtmlHelper extensions from Razor declarative views You'll probably want to over the default helper page with this (and inherit in your helper classes in App_Code)

public class WorkaroundHelperPage : HelperPage
    {
        // Workaround - exposes the MVC HtmlHelper instead of the normal helper
        public static new HtmlHelper Html
        {
            get { return ((WebViewPage)WebPageContext.Current.Page).Html; }
        }

        public static UrlHelper Url
        {
            get { return ((WebViewPage) WebPageContext.Current.Page).Url; }
        }
    }
Community
  • 1
  • 1
dove
  • 20,469
  • 14
  • 82
  • 108
1

I would make a helper for this, something like this:

using System.Web.Mvc.Html;
public static class HtmlHelpers
{
    public static MvcHtmlString LabelDisplayFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
    {
        StringBuilder html = new StringBuilder();
        string disp = helper.DisplayFor(expression).ToString();
        if (!string.IsNullOrWhiteSpace(disp))
        {
            html.AppendLine(helper.DisplayNameFor(expression).ToString());
            html.AppendLine(disp);
        }
        return MvcHtmlString.Create(html.ToString());
    }
}

Now, when you are in your View, you can simply do this (given you include the namespace in your view or web.config):

@Html.LabelDisplayFor(model => model.FormattedTelephone)

All it really does is check to see if your display helper is not an empty string, if it is, it will simply append your LabelFor and DisplayFor, if not, it will return an empty string.

radu florescu
  • 4,315
  • 10
  • 60
  • 92
naspinski
  • 34,020
  • 36
  • 111
  • 167
  • I am getting an error on DisplayFor and LabelFor 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'LabelFor' and no extension method 'LabelFor' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' – Stephen Sep 26 '12 at 09:31
  • Odd, you must be on a different version? Looks like you are using 'DisplayNameFor' (edited) – naspinski Sep 26 '12 at 13:59
  • Updated code changing LabelDisplayFor and DisplayFor to DisplayNameFor and now no errors. Will test it. – Stephen Sep 26 '12 at 15:03
  • Getting a compilation error CS0121: The call is ambiguous between the following methods or properties: MyProject.Helpers.HtmlHelpers.DisplayNameFor and System.Web.Mvc.Html.DisplayNameExtensions.DisplayNameFor – Stephen Sep 26 '12 at 15:27
  • You have to change your methods name to something other than DisplayNameFor – naspinski Sep 26 '12 at 15:28
1

I usually prefer to use Display/Editor Templates instead of HtmlHelper. Here is template that I have used to perform exactly the same task, its designed for bootstrap data list but anyone can adjust it easily.

@if (Model == null)
{
    @ViewData.ModelMetadata.NullDisplayText
}
else if (ViewData.TemplateInfo.TemplateDepth > 1)
{
    @ViewData.ModelMetadata.SimpleDisplayText
}
else
{
    <dl class="dl-horizontal">
        @foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForDisplay && !ViewData.TemplateInfo.Visited(pm)))
        {
            if(MvcHtmlString.IsNullOrEmpty(Html.Display(prop.PropertyName)))
            {
                continue;
            }    

            if (prop.HideSurroundingHtml)
            {
                @Html.Display(prop.PropertyName)
            }
            else
            {
                <dt>@prop.GetDisplayName()</dt>
                <dd>@Html.Display(prop.PropertyName)</dd>
            }
        }
    </dl>
} 

Key line is:

if(MvcHtmlString.IsNullOrEmpty(Html.Display(prop.PropertyName)))

Its based on object template so to use it you need use it on object or whole model like

@Html.DisplayForModel("TemplateName") 
Machet
  • 1,090
  • 8
  • 17