William
William

Reputation: 3395

View for Object with Nested Classes

I am trying to create a few for an object that contains references to other objects.

For instance,

public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
    public ICollection<Subscription> Subscriptions { get; set; }
}

public class PersonSubscription
{
    [Key, Column(Order = 1)]
    public int PeopleID { get; set; }
    public Person People { get; set; }

    [Key, Column(Order = 2)]
    public int SubscriptionID { get; set; }
    public Subscription Subscription { get; set; }
}

public class Subscription
{
    public int ID { get; set; }
    public string Magazine { get; set; }
    public ICollection<PersonSubscription> Subscriptions { get; set; }
}

In the above example, when I am creating a new Person, I want to allow that person to be added to several new or existing subscriptions. So this means that somehow the view needs to be made aware of the existing subscriptions in the system. Also, in a related note, when a subscription is added that did not previously exist, it needs to create a new instance and add it to all of the appropriate databases.

I might be overthinking this - I have considered creating a custom model binder (enter link description here), but I am not sure whether that would be overkill for this.

Upvotes: 0

Views: 75

Answers (1)

danludwig
danludwig

Reputation: 47375

I wouldn't do this with a model binder. Model binding is an infrastructure concern that is handled pretty well by the framework's DefaultModelBinder. Use custom model binders when you need to do something like bind to a model without a no-arg constructor, or automatically populate properties from the request or http context.

When you say that you want a person to be added to 1 or more subscriptions, this is a business rule in your system, not an infrastructure concern. So doing it with a custom model binder would be a misuse of the model binding customization hook. The appropriate place to do this is either in the controller action that accepts the request to create a new person, or some lower layer, not the MVC pipeline itself.

I don't think you're going to get a very helpful answer without a better description of what you're trying to accomplish though. Are you saying your view should have a text box for Person.Name, and possibly a list of Magazines with a checkbox next to each? And possibly another text box to enter a custom Magazine? Please clarify in your question.

Upvotes: 1

Related Questions