0

I have a very large set of controls that generates allot of Html content in the Response(HtmlTextWriter writer) method using HtmlTextWriter.WriteLine(format, params object[] args)

If I try to use this in MVC with a HtmlHelper I get the following

var ts = DateTime.Now;
using (var writer = new HtmlTextWriter(helper.ViewContext.Writer))
{
   writer.WriteLine("ToString(T) = " + ts.ToString("T") + "<br/>");
   writer.WriteLine("string.Format = " + string.Format("{0:T}", ts) + "<br/>");
   writer.WriteLine("WriteLine = {0:T}<br/>", ts);
}

ToString(T) = 9:27:07 AM
string.Format = 9:27:07 AM
WriteLine = 09:27:07 <=== This is in a 24 Hour Format

If I use "helper.ViewContext.HttpContext.Response.Output" instead then formatting is correct but the content is outputed above everything else in the view.

Also wondering if MVC aciont can output VIEW directy to Response Stream instead of generating large HtmlStrings

SIMPLE TEST DATA

This is not an MVC issue but perhaps a Razor issue, I'm able to replicate this in a simple cshtml file

@{
    var ts = DateTime.Now.AddHours(24 * 5 - 5);
}
ToString(T) = @ts.ToString("d") @ts.ToString("T") <br />
StringFormat = @string.Format("{0:d} {0:T}", ts) <br />
@using (var writer = new HtmlTextWriter(this.Output))
{
    writer.WriteLine("Output.WriteLine: {0:d} {0:T}<br/>", ts);
}
@using (var writer = new HtmlTextWriter(this.Response.Output))
{
    writer.WriteLine("Respone.Output.WriteLine: {0:d} {0:T}<br/>", ts);
}

RESULTS
Respone.Output.WriteLine: 1/4/2016 8:11:11 AM <== Correct but rendered at the top
ToString(T) = 1/4/2016 8:11:11 AM <== Correct
StringFormat = 1/4/2016 8:11:11 AM <== Correct
Output.WriteLine: 01/04/2016 08:11:11 <== Wrong format, this is 24HR
Steve
  • 1,995
  • 2
  • 16
  • 25

1 Answers1

1

This is a direct result of using HtmlTextWriter. If you have a look at the source code for it, it is hard coded to use the InvariantCulture.

public HtmlTextWriter(TextWriter writer) : this(writer, "\t")
{
}

public HtmlTextWriter(TextWriter writer, string tabString) 
    // Hard coded to the invariant culture
    : base(CultureInfo.InvariantCulture)
{
    // More initialization...
}

As far as I am aware it is not possible to override the culture with that of the current thread when using HtmlTextWriter.

One possible solution is just to use a plain TextWriter, which defaults to the culture of the current thread.

NightOwl888
  • 55,572
  • 24
  • 139
  • 212
  • So why does "new HtmlTextWriter(Response.Output)" format correctly? – Steve Dec 30 '15 at 20:04
  • The constructor is setting the culture on itself, but the formatting is controlled by the writer that is being passed in "this.writer.WriteLIne(format, args)", The Razor ViewContext.Writer is a StringWriter that has been set the the InvariantCulture. Not sure why this isn't set to the current culture. I will switch to RenderPartial as I want it to go directly to the output stream anyway – Steve Dec 30 '15 at 20:31