I’m creating a C# application using MVC 4, LINQ to SQL, and Razor Syntax.
I have created a class that gets the contents of a given row in the db based on a requested id.
I have made a controller that has a get and post handler. I created a strongly-typed view based on one of the model classes, and everything works great. Data is retrieved and displayed in the form. Data can be updated and submitted.
The problem is the dropdowns. I don’t want it to show a textfield for the id. I want the dropdowns. I have about five dropdowns, all to be generated from the database. I’ve created models to create them.
I can use ViewData or ViewBag to pass in the dropdowns with no problem. But then, how do I select the selected option when the user loads the page?
The “model” in MVC is supposed to model the page, not your data. If you have dropdowns on your page, then you should have a collection of some kind (likely a
List<T>) on your model that represents the choices, along with another property that represents the selected value. This property will be used to populate the initial value of the dropdown as well as send the selected value back up to the controller.