Search code examples
asp.net-mvcado.netentity-framework-4

Is it possible to save data into 2 tables using redirect to? Without Viewmodel


I have an issue, and I don't know what to do.

I have 2 tables that have a relationship between them (PK - FK), and I want to know if it's possible to add a new row in the first table then redirect that to the second table, and then add another new row then save data in both tables?

I have tried to do this but it's only inserting a new row just in the first, the second lets me enter data but when I save, it doesn't save in the second.

I have 2 separate controllers for each table but that is really what I want to know if it is possible and how. A basic example is really appreciated. Please bear in mind that I'm quite new at programing whit this technology.

Thank you, and sorry for any bad spelling!


Solution

  • Your question is very unclear. Are you looking for a way to save all the data at once or just create a workflow where the user can enter in both sets of data?

    To save the data all at once you have two options. The first and best option is to simply include all the fields for both entities in one form. There doesn't have to be a 1-1 correlation between a controller and particular entity. You can work with multiple different entities in a single controller action. Utilizing a view model, you can work with all the data in one view and then map the posted information to all the appropriate entities and save them all at once.

    The second option is to create a "wizard" or multi-step form. Since each request is idempotent, you just have to persist the data from each post in some way, generally TempData. In the final step, you can then retrieve the previous posted data from TempData or wherever else you persisted it and finally save all the entities.

    If you're talking about two separate save steps as part of a work flow, that's even easier. You just follow the PRG (Post-Redirect-Get) pattern and just make your redirect the next step in the chain. However, this only directs the user down a defined path. It does not prevent the user from breaking the chain and failing to complete later steps.