Jean-Francois
Jean-Francois

Reputation: 1949

Asp.net MVC 4, How making Master Detail in the same form

I use entity Framework 4.2 and MVC 4

I Got this model/Database structure

UserInformation
UserID(PK)
FirstName
LastName
Email


UserFavoriteColor
FavID(PK)
Color
Why
UserID(FK)

Is it possible in one Create Controller Action to fill the UserInformation table and then Fill the UserFavoriteColor.

I Know I could perform this in two steps by creating 2 separates sectiosn. But this is not what I want.


enter image description here

Upvotes: 5

Views: 10986

Answers (1)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

Typically, you would use jQuery to insert a new row. Since we don't know what your code looks like, it's hard to show you exactly how this should be done, but you can look at the examples here:

http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/

The trick is that you have to name them appropriately so that the model binder will add them to your collection when you click save. Then you have to write code in your post method to walk through the list of colors and add any records that don't exist already.

This is a relatively complex thing, so it's not something that can be easily covered in a single answer here.

Another option is to simply have an action for the add-new button, and this inserts a blank record into the data collection, which on postback will now get 3 records (one of them with null values). When you fill in the values, it will then postback to the main post method and udate the blank record.

This solution has the drawback that if the user adds a new record and doesn't save, the blank record stays in the database.

Upvotes: 7

Related Questions