Passing ViewModel for backbone.js from MVC3 Server-Side

Posted by Roman on Stack Overflow See other posts from Stack Overflow or by Roman
Published on 2011-11-17T17:29:59Z Indexed on 2011/11/17 17:51 UTC
Read the original article Hit count: 203

In ASP.NET MVC there is Model, View and Controller.

MODEL represents entities which are stored in database and essentially is all the data used in a application (for example, generated by EntityFramework, "DB First" approach).

Not all data from model you want to show in the view (for example, hashs of passwords). So you create VIEW MODEL, each for every strongly-typed-razor-view you have in application. Like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyProject.ViewModels.SomeController.SomeAction
{
    public class ViewModel
    {
        public ViewModel()
        {
            Entities1 = new List<ViewEntity1>();
            Entities2 = new List<ViewEntity2>();
        }

        public List<ViewEntity1> Entities1 { get; set; }
        public List<ViewEntity2> Entities2 { get; set; }

    }

    public class ViewEntity1
    {
        //some properties from original DB-entity you want to show
    }
    public class ViewEntity2
    {

    }
}

When you create complex client-side interfaces (I do), you use some pattern for javascript on client, MVC or MVVM (I know only these). So, with MVC on client you have another model (Backbone.Model for example), which is third model in application. It is a bit much.

Why don`t we use the same ViewModel model on a client (in backbone.js or another framework)? Is there a way to transfer CS-coded model to JS-coded? Like in MVVM pattern, with knockout.js, when you can do like this:

in SomeAction.cshtml:

<div style="display: none;" id="view_model">@Json.Encode(Model)</div>

after that in Javascript-code

var ViewModel = ko.mapping.fromJSON($("#view_model").get(0).innerHTML);

now you can extend your ViewModel with some actions, event handlers, etc:

ko.utils.extend(ViewModel, {

some_function: function () {
//some code
}

});

So, we are not building the same view model on the client again, we are transferring existing view model from server. At least, data.

But knockout.js is not suitable for me, you can`t build complex UI with it, it is just data-binding. I need something more structural, like backbone.js.

The only way to build ViewModel for backbone.js I can see now is re-writing same ViewModel in JS from server with hands.

Is there any ways to transfer it from server? To reuse the same viewmodel on server view and client view?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about asp.net-mvc