Quantcast
Channel: ClearScript
Viewing all articles
Browse latest Browse all 2297

New Post: Passing DateTime from c# to javascript function

$
0
0
Greetings!

As you've noticed, ClearScript doesn't automatically convert DateTime instances into JavaScript dates; such conversion is lossy and not always desirable. However, because it's often useful, we recommend the following.

First, here's a general-purpose class for lazily evaluating a JavaScript expression and caching the result:
publicclass CachedJsValue {
    privateclass Holder { publicobject Value; }
    privatereadonly ConditionalWeakTable<ScriptEngine, Holder> table = new ConditionalWeakTable<ScriptEngine, Holder>();
    privatereadonlystring expression;
    public CachedJsValue(string expression) {
        this.expression = "(" + expression + ").valueOf()";
    }
    publicobject Get(ScriptEngine engine) {
        var holder = table.GetOrCreateValue(engine);
        if (holder.Value == null)
            Interlocked.CompareExchange(ref holder.Value, engine.Evaluate(expression), null);
        return holder.Value;
    }
    publicdynamic GetDynamic(ScriptEngine engine) {
        return Get(engine);
    }
}
And here's a class that uses it to define a ToJsDate extension method for DateTime:
publicstaticclass DateTimeScriptExtensions {
    privatestaticreadonly CachedJsValue createDateFunc = new CachedJsValue(@"
        function (y, m, d, h, min, s, ms) {
            return new Date(y, m, d, h, min, s, ms);
        }
    "); 
    publicstaticobject ToJsDate(this DateTime dt, ScriptEngine engine) {
        return createDateFunc.GetDynamic(engine)(
            dt.Year, dt.Month - 1, dt.Day,
            dt.Hour, dt.Minute, dt.Second, dt.Millisecond
        );
    }
}
Finally, your sample code can look like this (with a few tweaks and recommended simplifications):
var engine = new V8ScriptEngine();
engine.Execute(@"
    function my_func(props) {
        var m_date = props.my_date;
        var m_code = props.my_code;
        var yeay = m_date.getFullYear();
        return yeay;
    }
");
var properties = new PropertyBag();
properties["my_code"] = 20;
properties["my_date"] = DateTime.Now.ToJsDate(engine);
Console.WriteLine(engine.Script.my_func(properties));
Good luck!

Viewing all articles
Browse latest Browse all 2297

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>