This example I have been struggling with best practice for a while and I cannot seem to get it right. Here is the model that I am trying to accomplish on the view and then bind it to a model in a post. It is a test
a test has several attributes as well as a collection of testItems
(one-to-many relationship)
The code of the models for the above form would be as so:
public class Test
{
public int TestID { get; set; }
public virtual ICollection<TestItem> TestItems { get; set; }
}
public class TestItem
{
public int TestID { get; set; }
public int TestItemScore { get; set; }
public int? TestID { get; set; }
public virtual Test Test { get; set; }
}
Currently My methods for posting the form would be to make a post method
that takes a model and then two arrays, one of questions and one of answers, then those are made into objects in the post function and then added to the model that I passed to the function like so.
public ActionResult PostATest (Test test, string[] questions, string[] answers){
//create a list of test.testItems
//create a new test item class
//loop over the array of questions and add an answer and question to the test item class
//add the test item to the test
//repeat until all questions and answers are added to new object
//save the test object to the db context.
db.tests.save(test);
}
So the code above is how I have been doing most of these general practices, but there are serious problems with this, especially when going back and trying to make a model that I can edit.
Most of the html has to be done by hand using similar variable names to make the string arrays bind-able.
Ideally I would like to have a function in my post that is simply (the function below) that would know that there are many to one models inside that one model. It needs to be flexible so that when the form is submitted that it automatically creates the test Model and gives it to the post and it also creates the testItem model.
public actionResult testPost(Test test){
}
or at the very least have a post that posts like this maybe
public actionResult testPost(Test test, TestItem[] testItem){
}
I have been doing this the way that the first post method above suggests for about a month and I cannot seem to find ANY other way to do this without making each item on the test its own form.
A thorough way to solve this problem would be greatly appreciated. The code provided is just example code, if some of my actual implemented code is required, just ask. I have done this in several different contexts and there has to be a better way to tackle this problem.
The biggest problem with the way that I am currently doing it is that it makes it tremendously difficult to go back and edit a form later with the way that I am doing it now.
Please note any questions that you may have on how I have asked my question in the comments or if there is anything that I need to make a little more clear.