This question is similar, but with no conclusion and a self accepted answer of "no": automatically generate javascript object model from c# object
This answer by Darin is a very good example of mapping an object to Json, although I am not sure if it works with complex models: https://stackoverflow.com/a/9007578/1026459
Here is an example of what I was looking at. Given this setup:
Viewmodel:
public class Avm
{
public int id { get; set; }
public string name { get; set; }
public Foo Foo { get; set; }
}
public class Foo
{
public int id { get; set; }
public string description { get; set; }
public List<Bar> Bars { get; set; }
}
public class Bar
{
public int id { get; set; }
public string metal { get; set; }
}
Is there a possible way to define this object model:
javascript object model:
<script>
var Avm = {};
Avm.id = @(Model.id);
Avm.name = "@(Model.name)";
Avm.Foo = {};
Avm.Foo.id = @(Model.Foo.id);
Avm.Foo.description = "@(Model.Foo.description)";
Avm.Foo.Bars = [];
var Bar = function(){
return
{
id : var id,
metal : var metal;
};
}
var Bar0 = new Bar();
Bar0.id = @(Model.Foo.Bars[0].id);
Bar0.metal = "@(Model.Foo.Bars[0].metal)";
Avm.Foo.Bars.push(Bar0);
//and so on for each Bar.
</script>
Through a more precise method than just typing it all out by hand?
Or, perhaps through some sort of reflection in a helper so that it would become
<script>
@Html.GenerateJsObjectModel(Model)
<script>
Which would call a helper method
public static void GenerateJsObjectModel(
this HtmlHelper html, dynamic model)
{
html.ViewContext.Writer.Write("var Avm = {};");
html.ViewContext.Writer.Write("Avm.id = " + model.id + ");");
//etc. (except obviously more generic instead of specific)
}
Does this already exist in the framework? Would using a serialization process like JSON be superior here and if so what type of hook would be used to tie JSON in for this scenario?
What is the best practice approach for creating a complex model in javascript based on a viewmodel.