0

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);
    }
J0NNY ZER0
  • 707
  • 2
  • 13
  • 32

1 Answers1

1

I can only see two options in this scenario:

  1. Pre-fill the Object1 GUID in the model, when you post it back from the view, just like the other properties. This could be accomplished different ways depending on your requirements (user-selected drop-down, pre-populated into a hidden field, etc).
  2. Keep track on the server of which Object1 the current user is working on. You might do this using the Session object, or even using TempData.

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.

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • Ideally on the detail view of Object1, I want an action button that the user can click to create Object2. So an association should be made from that. Possible that step 1 could accomplish part of this? Can you point me to any examples on the web or from your experience? – J0NNY ZER0 Jun 24 '12 at 05:53
  • @HelloJonnyOh I added some details to my answer for that scenario, please check my update. – McGarnagle Jun 24 '12 at 06:04
  • @MyAddView that would be your existing view used for adding a new *Object2* (in this case I'm assuming you are using the *Object2* model itself as the view model). – McGarnagle Jun 24 '12 at 06:32
  • If my first view has @Html.HiddenFor(Model => Model.Object1Id) and the link in my first view is generated using @Html.ActionLink("Create", "Create", "Object1", new { area = "Area1" }) then how could I make the Object1Id available so the Create() method in my Object2 controller can access the Object1Id? – J0NNY ZER0 Jun 24 '12 at 07:30