I am very confused by how to accomplish this, I have seen these: reference to similar question 1 & reference to similar question 2 None of these two question answers explain
First, get this code out of your controller. In MVC controllers should be thin – their responsibility should be figuring out which View to render and passing data to and from the Views and the business layer. Second, your View is strongly typed to the OurColumns object an instance of the OurColumns object is never passed the view. It looks like you need a ViewModel that has a collection of DCResults for your DropDownList and a string to capture the selected value. It is not strictly necessary to have a separate “Selected” item, but I like how it simplifies code – it’s a ViewModel after all.
public class ViewModel {
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public List DCResults { get; set; }
public string SelectedDCResult { get; set; }
}
Your controller should be responsible for creating the View Model on the GET request and parse the ViewModel into the Business Object (or past that along to a service in a more layered application).
public ActionResult Get()
{
var model = new ViewModel {
DCResults = this.DcResultRepos.DCResults
};
return View(model);
}
public ActionResult Post(ViewModel model) {
if (ModelState.IsValid) {
//do something
}
return View("Another View");
}
If you are not using an ORM for persistent storage to object binding, then you will need to create your own, in another class so you can abstract away that binding from the WebUI. For the previous example, I used the following signature:
private class DCResultRepository {
public List DCResults { get; }
}
In the body of the get (or helper method) you could process your DataTable and use yield return to create an IEnumerable that would allow you to use Linq in your controller. Like this:
private DataTable table;
public IEnumerable DCResults {
get {
//do something to get datatable
foreach(var row in table.Rows){
yield return new Model(){
//initialize values
};
}
}
}