Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: Binding a Complex Type to a Select

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.

like image 238
Gavin Osborn Avatar asked Feb 16 '09 22:02

Gavin Osborn


People also ask

What is bind property in MVC?

ASP.NET MVC framework also enables you to specify which properties of a model class you want to bind. The [Bind] attribute will let you specify the exact properties of a model should include or exclude in binding.

How data binding can be used in ASP NET MVC?

ASP.NET MVC model binding allows mapping HTTP request data with a model. It is the procedure of creating . NET objects using the data sent by the browser in an HTTP request. Model binding is a well-designed bridge between the HTTP request and the C# action methods.

Does MVC use data binding?

asp.net mvc supports data binding. You can bind data to some model and post it back when the form is submitted.


1 Answers

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

like image 58
Mauricio Scheffer Avatar answered Nov 15 '22 17:11

Mauricio Scheffer