I have a constants values such as “Required”,”Optional”, and “Hidden”. I want this to bind in the dropdownlist. So far on what I’ve done is the below code, this is coded in the view. What is the best way to bind the constant values to the dropdownlist? I want to implement this in the controller and call it in the view.
@{
var dropdownList = new List<KeyValuePair<int, string>> { new KeyValuePair<int, string>(0, "Required"), new KeyValuePair<int, string>(1, "Optional"), new KeyValuePair<int, string>(2, "Hidden") };
var selectList = new SelectList(dropdownList, "key", "value", 0);
}
Bind the selectList in the Dropdownlist
@Html.DropDownListFor(model => model.EM_ReqTitle, selectList)
Judging by the property
EM_RegTitleI’m guessing that the model you’re using is auto-generated from a database in some way. Maybe Entity Framework? If this is the case, then you should be able to create a partial class in the same namespace as your ORM/Entity Framework entities and add extra properties. Something like:You can then pass your
SelectListwith the rest of the model.There are usually hangups from using ORM/EF entities through every layer in your MVC app and although it looks easy in code examples online, I would recommend creating your own View Model classes and using something like AutoMapper to fill these views. This way you’re only passing the data that the views need and you avoid passing the DB row, which could contain other sensitive information that you do not want the user to view or change.
You can also move the logic to generate your static value Select Lists into your domain model, or into a service class to help keep reduce the amount of code and clutter in the controllers.
Hope this helps you in some way!
Example…
Your View Model (put this in your “Model” dir):
Your Controller (goes in the “Controllers” dir):
Now right click the
SimpleControllerclass name in your editor and select “Add View…”.Create a new view, tick strongly typed and select your
MyViewModelclass as the model class.Now edit the view and do something similar to what you were doing earlier in your code. You’ll notice there should now be a
@modelline at the top of your view. This indicates that your view is a strongly typed view and uses theMyViewModelmodel.If you get stuck, there are plenty of examples online to getting to basics with MVC and Strongly Typed Views.