Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting line breaks in DisplayName attributes

In my ViewModel there is a property that needs a 2 line label but when I place a <br /> in the DisplayName attribute the HTML code is printed to the page instead of being interpreted as a line break. Is there a way to get a DisplayName to have a line break in it?

View:

    <tr>
        <td>
            @Html.LabelFor(m => m.GrossGallons)
        </td>
        <td>
        </td>
    </tr>

ViewModel:

    [DisplayName("Gross Gallons <br /> (Max: 6,000)")]
    public decimal GrossGallons { get; set; }

Output trying to get:

Gross Gallons
(Max: 6,000)
like image 884
Matthew Verstraete Avatar asked Mar 12 '14 14:03

Matthew Verstraete


2 Answers

There is a simple way of doing this - use \n instead of <br />, and use CSS to make it work.

Model:

[DisplayName("Gross Gallons\n(Max: 6,000)")]
public decimal GrossGallons { get; set; }

CSS:

label { white-space: pre-wrap; }

I would recommend making the CSS selector as specific as possible, so as not to catch other labels (in case you're using labels by hand elsewhere, where your source code may contain whitespace). For example, in bootstrap I would've applied this to label.control-label.

You could also attach a more specific style to that label only, and style only that class.

@Html.LabelFor(m => m.GrossGallons, new { @class = "multiline-label" })
like image 62
Richard Avatar answered Nov 16 '22 05:11

Richard


I can think of a few options.

1) You could use @Html.Raw(). You can replace the string I have entered with a reference to a string.

@Html.Raw("Gross Gallons <br /> (Max: 6,000)");

1a) If you need to set it in the DisplayName attribute, then you might try using Html.Raw() but accessing the value through reflection. (Note: I haven't tried this, so don't know if it is possible)

2) You could use css styling to force the line to wrap where you want it to.

3) You could create a custom extension method or custom attribute to do this for you.

like image 1
ken4z Avatar answered Nov 16 '22 04:11

ken4z