Being fairly new to web dev and MVC4, I am encountering the same design issue repeatedly and was hoping someone could tell me what the right/supported/etc.. solution was in the MVC4 world:
Basically, I've drunk the view model koolaid and have view models for every view in my project, most of which are partial subviews dynamically updating on something of a single page application. All proceeds well generating/rendering the view, and then a user updates a number of values on the client side and it's time to update the server.
As an example, let's say it's a simple container view model:
public class Data {
public List<Prop> Props { get; set; }
}
public class Prop {
public string Id { get; set; }
public int Value { get; set; }
}
So let's just say the user is adding new props to the container. How do I get the modified object back to the server?
So far: If it's important that the server be in sync realtime, I can make a call with each addition/update on the server and then either keep things in sync on the client or simply have the server return the updated view. For simple scenarios like that, all is well.
But I find myself often in the case where I want the client to be able to manipulate the object (through the view/js/etc) and I don't really need to update on the server until they are done and submit. What I really want is to be able to pass the object down with the rendered view, interact with it via Javascript, and then pass the object back to the controller when all is done. How do I that? (Apologies it took a while to get to the point!)
Alternatives I've seen:
-- Quick & Dirty (Encode viewmodel properties to JavaScript in Razor): Which sure will put the object in javascript on the client, though it seems hack-ish to just be serializing the whole object into the client side html without any validation, etc. (Though I do realize eventually that's how the object is making it's way down, but it seems like you're bypassing the whole MVC4 object handling/parsing.)
-- Upshot.Js seemed promising with MS support at one time, but it seems that has died: Current status of Upshot.js
-- Breeze.js (http://www.breezejs.com/) seems to be an attempt to take over there, though my concern there is that it's fairly new and not much broad adoption yet.
Ultimately the thing that makes me feel like I'm missing what must be a somewhat obvious alternative is that all the pieces are clearly built into MVC4 already. When you use a form view for example, your fields are databound to the controls, and when the form is submitted, a parallel JSON object is created, sent to the controller, and then parsed into your POCO ViewModel object for you. That's basically the roundtrip I'm looking for (though retaining the full JSON object clientside). What's the "proper" way to handle that?