Created
July 30, 2014 08:50
-
-
Save lski/cda0863b0b71b3c1602a to your computer and use it in GitHub Desktop.
Mvc Helper for dumping raw javascript to a view (handles raw dates too)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Web.Mvc; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Converters; | |
public static class HtmlHelperExtensions { | |
/// <summary> | |
/// Dumps a JSON object to a view, in javascript format rather than as a string | |
/// </summary> | |
public static MvcHtmlString ToRawJavascriptObj(this HtmlHelper helper, object obj) { | |
return new MvcHtmlString(JsonConvert.SerializeObject(obj, new DateTimeUTCRawConverter())); | |
} | |
/// <summary> | |
/// Simple convertor class for writing Json dates as raw Javascript (new Date() not a ISO8601) | |
/// </summary> | |
private class DateTimeUTCRawConverter : DateTimeConverterBase { | |
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { | |
return DateTime.Parse(reader.Value.ToString()); | |
} | |
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { | |
var dat = ((DateTime)value); | |
writer.WriteRawValue(String.Format("new Date(Date.UTC({0},{1},{2},{3},{4},{5}))", dat.Year, dat.Month - 1, dat.Day, dat.Hour, dat.Minute, dat.Second)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment