tags:

views:

331

answers:

2

I've got a simple structure

Widget (parent table)

  • id (IDENTITY)

  • title

WidgetChild (child table) -

  • id (foreign key to widget.id)
  • content

On my View i have one field that captures the title, and another field that captures the content value.

 <%= Html.TextBox("title") %>

and

 <%= Html.TextBox("content") %>

How do i go about wiring up my controller to insert a new entry into Widget first and then insert an entry into WidgetChild? I'm not sure how to go about doing this.. do I pass a FormCollection instance, manually instantiate the Widget instance and pass in the values? Or can i use UpdateModel() somehow? I'm not familiar with how UpdateModel could bind my form values especially if they span multiple tables/classes.

A: 

You need to differentiate two process as per your database structure. you can use a wizard step. check this link.

Second way is to do it manually. Like on page submit you will get all page data in action method which accepts post verb, right. Now you can do entry in parent table with filling required fields and then immediately fetch same record to get the primary key. And at last you can enter data in child table with using parent table ID.

Don't you think this process is a headache! It is better to add child content in another view where you can show dropdown for widget parent and then add content.

Vikas
+1  A: 

You could use automatic model binding here.

With a form like this:

<%using(Html.BeginForm("Update", "Home")) {%>
    <%=Html.TextBox("widget.Title") %>
    <%=Html.TextBox("childWidget.Content") %>
    <input type="submit" value="Submit" />
    <%} %>

Your controller can then look like this:

public ActionResult Update(Widget widget, WidgetChild childWidget)
{
  // do whatever with the objects here
}

The objects will have the properties from the form populated there (Title for widget, and Content for childWidget) - then you can associate these objects with each other and save them to your linq to sql data context in the normal way.

Steve Willcock