Label shortcut point

I use mvc5 in combination with a razor and populate the site text dynamically based on the language. Example:

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

@DDHelper.GetContent("user_name") returns a string that is specified as the label text. when @DDHelper.GetContent("user_name") returns "Hello." no label is created and the html source is empty.

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

+6
source share
2 answers

Check the overloads for @ Html.Label, the one you are using:

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

the one you want

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

There is a general misunderstanding of what an HTML label . In winforms, the label is the place where you put the text - this is not the case in HTML. In HTML, a <label> allows the user to click on your text and point the focus / cursor point to the corresponding input.

Full syntax for label:

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

Part of the expression in the above overloads is part of the "for" in html - it must point to the name of the control.

If this is what you are trying to do (connect the label to the control), try:

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

If your input is called 'user_name'. Here @Html.LabelFor comes in, something like:

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

so that you do not specify hardcode field names and refactoring.

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

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

but since you are using a "check mark", I suspect you want <label> .

+9
source

If Html.Label (..) is not an option, I would suggest an alternative:

 <h4>@Html.Encode(@DDHelper.GetContent("user_name"))</h4> 

Worked well for me.

0
source

Source: https://habr.com/ru/post/987056/


All Articles