19

I am trying to work out if there is built-in support for binding complex types to form elements.

To use a common hypothetical situation: I have a Product entity that belongs to a Category - the models look something like this:

public class Product
{
    public int ID { get; set; }
    public string Description { get; set; }
    public Category Category { get; set; }
}
public class Category
{
    public int ID { get; set; }
    public string Title { get; set; }
}

Creating a form to hydrate a new entity that only contains simple value types is nice and simple using the ASP.Net MVC framework, e.g.:

public ActionResult Create(Product product);

But what about the above scenario where your entities contain other complex types? Are there built-in mechanisms for binding an IEnumerable<T> to a drop down list and then automatically hydrating the correct T when the form is submitted?

It would be fairly trivial to do it manually - I'm just trying to ascertain what I can have for free out of the box.

Pang
  • 9,564
  • 146
  • 81
  • 122
Gavin Osborn
  • 2,593
  • 3
  • 27
  • 42
  • See [here](http://weblogs.asp.net/scottgu/archive/2008/10/16/asp-net-mvc-beta-released.aspx#three) and [here](http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx) and [here](http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx) for details about model binding. – zihotki Feb 17 '09 at 00:07

3 Answers3

2

Please check this, as I think that talks about your question, it seems that the S#arp guys have solved it and it's easily "rip"'able if you don't use their stuff.

Anyway I think it's somewhat dangerous to automatically load entities from whatever the user posts... will have to think about it.

Francisco Lozano
  • 372
  • 4
  • 12
2

I haven't yet tried the DefaultModelBinder for complex types, but you could always use MvcContrib's CastleBind (borrowed from the Castle Project) which gives you complex type binding easily, including arrays.

See http://blogger.forgottenskies.com/?p=258

Mauricio Scheffer
  • 98,863
  • 23
  • 192
  • 275
1

The closest I think that it will come is overriding the ToString() method in the class to output meaningful information to the DropDownList - but not much else.

You may be able to bind the IEnumerable collection to a DropDownList and then retrieving its SelectedItem when the form is submitted - that is the cheapest way I can think of.

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Fritz H
  • 3,539
  • 2
  • 26
  • 37