Search code examples
asp.net-mvc-3unicoderazorrenderpartial

Bizarre hidden character in MVC3 Razor loop


I have a loop

<ul id="news-list" class="thumbobs-list">
    @foreach (var item in Model.News) {
        @Html.Partial("RenderNews/" + item.TypeString, item)
    }
</ul>

that uses partials like this

@model Web.Models.DataModel.NewsItem
@{ Layout = null; }
<li class="news-item @Model.TypeString.ToLower()" id="id-@Model.Id">
   <h3 class="headline">
     Example News headline.
   </h3>
   <p class="timestamp">@Model.TimeString</p>
</li>

that works great

but when i went to style with css i encountered a hidden whitespace character that is causing an issue

in front of each partial a space, a U+FEFF, and another space causing issues with the design.

has anyone ever seen this?


Solution

  • You have discovered the BOM, Byte Order Mark. It's stored as the first bytes in text files to indicate the encoding.

    http://en.wikipedia.org/wiki/Byte_order_mark

    [EDIT]

    You can open a file with Notepad and "Save As..." as ANSI. This removes the BOM (and the encoding).

    // reading a text file as binary will include the BOM flag
    FileStream FS = new FileStream(MapPath(@"~\Text\TestUTF8.txt"), FileMode.Open);
    
    byte[] Data = new byte[100];
    
    FS.Read(Data, 0, 100);  // BOM is in the data
    FS.Close();
    
    // get rid of the BOM
    String String1 = System.Text.Encoding.UTF8.GetString(Data);
    
    // reading a text file as text will automatically handle it.
    String String2 = File.ReadAllText(MapPath(@"~\Text\TestUTF8.txt"));