John
John

Reputation: 6553

What is the best way to handle creating, and updating Complex Datatypes in MVC3?

Ok I've been trying to figure out the best way to do this for a few days, but still haven't come up with a very elegant answer so am hoping I someone can point me in the right direction or give some peer review :)

Basically I have 3 classes (they are different and much more complex than these):

public class Person
{
    int ID { get; set;}
    string Name { get; set; }
    virtual IEnumerable<Place> { get; set; }

}

public class Place
{
    int ID { get; set;}
    string Name { get; set; }
    virtual IEnumerable<Thing> { get; set; }
}

public class Thing
{
    int ID { get; set;}
    string Name { get; set; }
    virtual IEnumerable<Place> { get; set; }
    virtual int PersonID { get; set; }
}

So basically you have Persons, who have many Places, which can have many Things which can also appear in multiple Places (trying to reduce having to store duplicates of Things) but only for that Person

What is the best way to setup my ViewModel to handle this? Should I just create everything by itself using Ajax and Json (what I've been doing) or is there a way to handle this type of relationship in a ViewModel and single post back to the server?

Currently I'm doing the following:

Fill out Person form -> ajax save to server, get Person ID

Fill out Place form (including Person's ID) -> ajax save to server, get Place ID

Fill out Thing form (including Person ID and Place IDs in a delimited string

I know there should be an easier way to do this as its kinda bulky, but since its all query string I can't figure it out

Upvotes: 2

Views: 119

Answers (2)

jkoreska
jkoreska

Reputation: 7200

You say "kinda bulky," but I think it tends to be more lightweight if you can build an object graph on a form in real time by using AJAX/JSON, probably against a RESTful API, somewhat as you describe.

The alternative is using script (jQuery, JSMVC, Knockout) to build a form and POST the whole sucker at once. I've had to do this in some situations where none of the data should be persisted until the whole graph is committed. The trick here is understanding ModelBinder and how it builds/updates that graph for you.

If this is what you were asking, I can expand on the key points of how ModelBinder deals with complex object graphs and collections.

Upvotes: 2

Erik Philips
Erik Philips

Reputation: 54638

I answered a similar question about how to handle this using interfaces and partial views.

How to create Asp.Net MVC 3 view model

Upvotes: 2

Related Questions