BuildJavaScriptDataModels is a small .Net library that will automatically generate a JavaScript Data Model that represents a .Net class. It works by scanning the public properties on the class and then outputs a JavaScript function that returns a copy of the new JavaScript Data Model for client side use.

Purpose

The inspiration for this project was using KnockoutJs to implement anMVVM pattern in the browser client. One requirement to use KnockoutJs efficiently is to have data models available on the client.

We found writing data models by hand in JavaScript to model our c# classes to be very tedious and prone to errors. This project is the result of trying to find a more efficient way to automatically generate the data models.

Usage

 

BuildJavascriptDataModel.Build is a static function that accepts the type of the class to build the JavaScript data model. It returns a string containing the full text of the data model.
Parameters
1st - This required parameter is the type of the class to generate the data model from
2nd - This optional parameter is the name of the JavaScript function that returns the data model. If this parameter is not supplied, then the name of the class is used instead

For Asp.Net MVC Users

There is also a set of HTML helpers for use in views.

 

<script type="text/javascript">
  $(document).ready(function () {
     @Html.BuildJsPrototype(typeof (NestedModel),
        "nestedModel")
     viewModel = {};
     var b = nestedModel();
     viewModel.model = ko.observable(b);
     });
</script>
All parameters are optional. If a type is not supplied, then the type of the Model in the strongly typed View is used.
Please notice that we are using an HTML helper method inside of a <script> tag.

 

 

Convert this c# class -

public class NestModelNestedClass
{
    public bool CheckBoxTest { get; set; }
    public int IntegerTest { get; set; }
}
public class NestedModel
{
    public NestModelNestedClass 
              NestModelSet { get; set; }
    public int IntProperty { get; set; }
    public string SimpleProperty { get; set; }
}

- Automatically to this JavaScritpt

//------------------------------------------------
//      Begin Auto Generated code ----------------
//      For Model Type - NestedMtodel   ----------
//------------------------------------------------
var nestedModel = function(){ 
     return {
        NestModelSet: { 
            CheckBoxTest: {},
            IntegerTest:  {}
            },
        IntProperty:  {},
        SimpleProperty:  {}
        }
    }
//------------------------------------------------
//      End Auto Generated code ------------------
//------------------------------------------------
KnockoutJs Users - The "{}" can be replaced with
     ko.observable()


Last edited Nov 6, 2011 at 5:17 PM by photo_tom, version 22