I am trying to make a ‘Create New’ page in MVC 4. The page will have text fields and dropdown fields. I want the items listed in the dropdown box to come from another model.
Main Model: (ignore syntax as following code is a generic example)
public int MainID {get; set;}
public int location {get; set;}
...
someDetails Model:
public int detailID {get; set;}
public int MainID {get; set;}
...
public int actionID {get; set;}
Action Model:
public int actionID {get; set;}
public int location {get; set;}
public string action {get; set;}
SomeDetails carries additional information about Main and is linked by using mainID. I am interested in creating a ‘Add Details’ pages for someDetails. Part of this page will include a dropdown for Action that is based on the location field in main.
What would be the best way to implement the dropdown box? I have a solution that involves passing possible values in the ViewBag, but I’ve seen this labeled bad practice. I was also thinking that it might be possible to change public int actionID {get; set;} to a type of <List>Action. If doing this method, I think I would have the constructor for someDetails populate the list? Would this cause performance issues when simply viewing a particular someDetails since it would try to create the list each time?
Create action:
public ActionResult Create(int id = -1)
{
if (id == -1)
{
//NOTE: INSERT REDIRECT HERE
}
someDetails model = new someDetails();
model.MainID = id;
return View(model);
}
EDIT:
As requested, better explanation of business logic
The main model I have shown is modeled after an existing table that I am not able to change as it is part of a data warehouse that lives outside my control/group. I am creating an application which allows users to add someDetails in order to gain better visibility/tracking of some of this data. The Action model simply displays possible actions/actionIDs based on the location.
My application will allow a user to search for or filter a set of items from the main model. They will be then allowed to add someDetails which will bring up a form which will contain some text fields and a dropdown list to pick an action. To get possible values for action, I would do something like SELECT * FROM Action a WHERE a.location = currentLocation
Just create a ViewModel with properties for each model… and that ViewModel can be populated in your controller and then passed to the view.
EDIT: For DropDownLists:
In your ViewModel you need a property for the selected action id, and another to the list itself.
In the model:
In the View:
In your controller: