Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor label dot period

I am using mvc5 in combination with razor and fill website text dynamically based on language. example:

@Html.Label(@DDHelper.GetContent("user_name"), htmlAttributes: new { @class = "control-label col-md-3" })

@DDHelper.GetContent("user_name") returns a string, which is set as a label text. when @DDHelper.GetContent("user_name") returns "Hello." the label is not created and the html source is empty.

I know this is because @HTML.Label() does not allow '.' and that's the root of my problem and that I should use @HTML.LabelFor() but how can i use @HTML.LabelFor() when i just want to display a string?

like image 298
Worst Avatar asked May 12 '15 13:05

Worst


1 Answers

Check the overloads for @Html.Label, the one you're using is:

public static MvcHtmlString Label(this HtmlHelper html, 
                                  string expression, 
                                  object htmlAttributes)

the one you want is

public static MvcHtmlString Label(this HtmlHelper html, 
                                  string expression, 
                                  string labelText, 
                                  object htmlAttributes)

There's a common misunderstanding of what an HTML label is. On winforms, a label is where you put some text - this is not the case in HTML. In HTML a <label> is to allow the user to click on your text and have the focus/cursor point to the corresponding input.

The full syntax for a label is:

<label for="controlName">caption</label>

The 'expression' part in the overloads above is the "for" part in the html - it must point to a control name.

If this is what you are trying to do (pair a label with a control) then try:

@Html.Label("user_name", 
            @DDHelper.GetContent("user_name"), 
            htmlAttributes: new { @class = "control-label col-md-3" })

Where your input is named 'user_name'. This is where @Html.LabelFor comes in, something like:

@Html.Labelfor(model=>model.UserName, 
               @DDHelper.GetContent("user_name"), 
               htmlAttributes: new { @class = "control-label col-md-3" })

so you don't hard-code field names and they refactor.

If you "just want to display a string" then you probably don't want a <label>. If you just need some simple text, you don't need an @Html anything and can just output the translation:

<div class='control-label col-md-3'>
    @DDHelper.GetContent("user_name")
</div>

but as you're using 'control-label' I suspect you do want <label>.

like image 153
freedomn-m Avatar answered Sep 21 '22 19:09

freedomn-m