Last post Dec 31, 2012 04:19 PM by bhardister
Dec 31, 2012 03:51 PM|bhardister|LINK
I'm new to MVC and Entity Framework. I'm using MVC4 Code First project with VS2012. The are three database tables: A, AB and B where AB consist only of A.ID and B.ID.
I want to insert into A. Here's the Get: Create method from the A controller:
public ActionResult Create(int id = 0) // id is the ID value of the row in the B table that I want to relate to
using (var context = new DEVContext())
B relatedB = context.B.FirstOrDefault(x => x.ID == id);
var a = new A();
This appears to work. When I debug the view I see that A includes a single count of B. My understanding is that I need to capture that data so when the user clicks the "Create" button on the form it will be passed to the HttpPost Create method. Here's the
code in my view:
@foreach (var item in A.B)
@Html.HiddenFor(modelItem => item.ID)
<input type="submit" value="Create" />
Here's where the problem appears. The relationship data does not make it to the HttpPost Create method. When I debug the code below I find that "a" has the data I entered on ther create form. But "a" is missing the missing the relationship
data (i.e. a.B) I passed in and saved in the form. I tried adding the relationship data in the HttpPost method, but the save throws an expcetion. I've been working on this for a couple of days and really need some help. Thanks!
public ActionResult Create(A a)
Dec 31, 2012 04:19 PM|bhardister|LINK
All it takes is to post it and then look for an alternative to find the answer!
Here's the working HttpPost methd with the solution in bold:
public ActionResult Create(A a, int bID)
B selectedB = db.B.Find(bID);