automatically generate javascript object model from c# object

前端 未结 4 855
南方客
南方客 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.

提交回复
热议问题