I’m pretty new to MVC 3 so I don’t know if this is possible. If it isn’t, what would be the best approach:
I have a Model1 with a lot of properties and a create view. In this page, people fill the needed data and do submit. But my problem is that the Model1 also contains SubModel1, which is another model (and another table in the database). I would want to offer buttons on the create page to create “on the fly” some SubModel1 via a pop-up CSS form and when the SubModel1 is submited, update the Model1 create page with a list of SubModel1 but :
- Since the Model1 is not currently saved, where would I save the Submodel when the Submit is done on the CSS pop-up form? Can I just add it to the Model1 model? If so, how?
- When I go back to the Create page, what to I need to do so it update and show the SubModel1 Names for example in a list.
- When I will do submit on the Model1, do I only need to save the Model1 and the rest will automatically save or do I need to do all the saving in the correct order myself in the controller?
Sorry if it’s newb question but it will help me a lot!
Thanks!
Like a lot of people say, there is no stupid question.
The problem you expose here is something that happens a lot and the solution is sometime simpler than we think.
There is more than one way to actually achieve what you want to do, but in my opinion, for a smoother experience, using JavaScript to display the PopUp and add the sub-item to the Model1 is the best option.
Your SubModel1 items should not be saved right away in your database for the simple reason that your Model1 might not be submited.
In this case your CSS popup should only really be a form (div or whatever) that exists in the page and use javascript to add a new row to the Model1 item.
Thus, when you submit the Model1 it will contain all the modifications, including the new SubModel1 items.
There is a naming convention to using to allow proper serialization of the form when submitting.
By sticking to this binding, this will allow you to wait for your Model1 in your controler.
How you save your items and sub items is depedant on how you access your data ( Entity Framework, linq-to-sql, classic ADO.NET or whatever suits your needs)
More Details : Some exemple on how to add the new elements
This is the kind of javascript that you will need to add the element (here I used a table to display the subitems)
For this example, the SubItems array is name like this :
Thus I know that when I add a new Item, the new names will be :
Once you submit, the server will bind the names to the properties in your Model.
You can see this in action on JsFiddle