automatically generate javascript object model from c# object

前端 未结 4 862
南方客
南方客 2021-02-12 14:42

Looking for existing, proven, solutions for quickly generating a client-side javascript object model that represents an existing c# object. I imagine there is a

相关标签:
4条回答
  • 2021-02-12 14:46

    This is an older question, but you could try sharp2Js. It's a library designed to reflect on your classes and generate javascript objects with a couple of utility functions.

    Running it against the example you provided (and outputting the string it produces in a T4 template or otherwise):

    string modelOutput = Castle.Sharp2Js.JsGenerator.
              GenerateJsModelFromTypeWithDescendants(typeof(Cat), true, "example");
    

    Produces:

    example = {};
    
    example.Cat = function (cons, overrideObj) {
        if (!overrideObj) { overrideObj = { }; }
        if (!cons) { cons = { }; }
        var i, length;
        this.name = cons.name;
        this.breed = cons.breed;
    
    
        this.$merge = function (mergeObj) {
            if (!mergeObj) { mergeObj = { }; }
            this.name = mergeObj.name;
            this.breed = mergeObj.breed;
        }
    }
    

    The extra metadata in there is some scaffolding to support collections and complex types with the ability to create inherited objects to override behavior, etc.

    Note: I am the maintainer of sharp2Js, and it's new and doesn't do a lot yet, but perhaps it can help for scenarios like yours.

    0 讨论(0)
  • 2021-02-12 14:55

    After countless searches I could not find anything close to what I’m looking for. Clearly everyone is caught up in the JSON buzz word the past few years and no one is auto-generating client-side object models. I looked at Codesmith and at T4 templates. Neither has any built in mechanisms for parsing code files. Both require you to jump into reflection to get at properties and their types which rests 100% on the developers shoulders. Which begs the question once you jump through that hoop of writing all that reflection code what benefit does Codesmith or T4 templates give you? Absolutely nothing.. You mind as well place your reflection code in a re-usable class library and call it from console application and that’s exactly what I’ve done.

    0 讨论(0)
  • 2021-02-12 15:01

    I am not sure if I could understand what you are talking about, but if you use Reflection you can obtain data about the C# code to generate information for the javascript object.

    0 讨论(0)
  • 2021-02-12 15:06

    I was thinking about the same idea and i searched a little bit about it i found this link maybe it's useful: http://igorshare.wordpress.com/2012/08/20/roslyn-c-is-cheating-on-me-with-javascript-or-how-to-compile-c-into-javascript/

    0 讨论(0)
提交回复
热议问题