I have 2 Models, each having many properties - Object1 and Object2
I have foreign key relationship with them in SQL db - Object1 can have many Object2's
Upon creating Object2 in my Object2Controller's Create() Method, how would I associate Object2 with Object 1's Guid?
Here is code:
Controller:
[HttpPost]
public ActionResult Create(Object2 object2)
{
if (ModelState.IsValid)
{
object2.Object2Id = Guid.NewGuid();
db.Object2.Add(object2);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(object2);
}
I can only see two options in this scenario:
Edit
To create a new Object2 from the Object1 detail view, follow this flow.
First, a simple form on the detail view:
@using (var form = Html.BeginForm("Add", "Object2Controller", FormMethod.Get))
{
<input type='hidden' name='Object1ID' value='@Model.Object1ID' />
<submit type='submit' value='Add Object1' />
}
Then you'll have an Add method in the controller for Object2 that pre-populates the foreign key:
[HttpGet]
public ActionResult Add(Guid Object1ID)
{
Object2 newObj = new Object2();
newObj.Object1ID = Object1ID;
return View("MyAddView", newObj);
}
This would point to the Object2 detail form, which posts back to the Create method in your question.