Why is @Html.Label() removing some characters

2019-02-09 03:57发布

问题:

When I use the following code in my razor view it renders <label for=""> someText</label> and not <label for="">1. someText</label> but I can't figure out why 1. is removed while rendering.

@Html.Label(String.Format("{0}. someText",1))

Edit: The following code renders <label for="">1# someText</label> as expected.

@Html.Label(String.Format("{0}# someText",1))

回答1:

You are misusing the Html.Label method. It is for:

Returns an HTML label element and the property name of the property that is represented by the specified expression.

That's why it gets confused if you have a point . in the first parameter because it expects a property expression there.

However, you can use the second overload:

@Html.Label("", String.Format("{0}. someText",1))

Or just write out the HTML:

<label>@String.Format("{0}. someText", 1)</label>


回答2:

You can avoid using the "Html Helper's label" and directly use html "label" and place whatever you want to display correctly. It can also save some time ;)



回答3:

The syntax which you are using is wrong or We can say that this is not a way to use property with RAZOR syntax. You ca use this that may be help full for you.

**

 @Html.LabelFor(model => model.PropertyName, 
       String.Format("{0}. " + @Model.PropertyName.ToString() + ",1))

**



回答4:

I was using this for a data table that contained a double (Lat/Long) and saw this same problem. Thanks for the tips (I am not allowed to comment).

For me, the problem was solved ..

@foreach (var cell in item.ItemArray)
{
  <td>
     @Html.Label("",cell.ToString().Trim())
  </td>
 }