MVC3 - Controller Method to Create Model Data and Associate with Guid from another Table / Model

StackOverflow https://stackoverflow.com/questions/11175177

Domanda

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);
    }
È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top