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
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 theInvariantCulture.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.