Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net mvc Display field in view only if it has a value

Tags:

asp.net-mvc

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.

like image 366
Stephen Avatar asked Feb 19 '23 01:02

Stephen


1 Answers

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>
    }
like image 167
Forty-Two Avatar answered Feb 22 '23 23:02

Forty-Two