Reputation: 82297
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.
Upvotes: 3
Views: 5375
Reputation: 16155
I'm partial of using the JavaScriptSerializer.
Not sure how to post Gists here so here is the link to the Gist with the pertinent pieces of code:
https://gist.github.com/3043237
Index.cshtml
@model JSSerializerSample.Models.IndexViewModel
@{
ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>
<div id="userName"></div>
<div id="message"></div>
<div id="complexProperty1"></div>
<script>
$(function () {
var options = @Html.Raw(Model.AsJson());
$("#userName").html(options.UserName);
$("#message").html(options.Message);
$("#complexProperty1").html(options.ComplexProperty.ComplexProperty1);
});
</script>
ComplexViewModel.cs
namespace JSSerializerSample.Models
{
public class ComplexViewModel
{
public string ComplexProperty1 { get; set; }
}
}
IndexViewModel.cs
namespace JSSerializerSample.Models
{
public class IndexViewModel : BaseViewModel
{
public string Message { get; set; }
public string UserName { get; set; }
public ComplexViewModel ComplexProperty { get; set; }
}
}
BaseViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
namespace JSSerializerSample.Models
{
public abstract class BaseViewModel
{
public string AsJson()
{
var serializer = new JavaScriptSerializer();
return serializer.Serialize(this);
}
}
}
The complete code sample can be downloaded here: https://github.com/devlife/Sandbox/tree/master/JSSerializerSample
Upvotes: 2
Reputation: 1578
Would something like this from the knockout.js library be what you were looking for?
Example JSON object:
var data = {"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
Example mapping
var viewModel = ko.mapping.fromJSON(data);
You could serialize the viewmodel to JSON server side and then use this to autogenerate the javascript viewmodel. You only have to call that ko.mapping.fromJSON(data) call each time you receive data from the server.
Link to the documentation (which is quite good): http://knockoutjs.com/documentation/plugins-mapping.html
Let me know if this helped/was what you wanted.
Edit: Here's a link to a good JSON serialization library that you can quickly demo by installing it through Nuget. http://json.codeplex.com/
Upvotes: 3
Reputation: 1507
It sounds less like you're trying to serve JSON, which as was noted in responses to your other post as purely for data transport, and more like you're trying to serve JSONP with MVC3.
Serving JSONP with MVC3 is imminently possible.
A tutorial for the server-side portion.
A CodePen example of the client-side portion.
Upvotes: 1