0

I am new in ASP.NET MVC, please excuse me if my question is too simple. I would like to create an ASP.NET MVC DropDownList with constant content, only with 4 items:"Patient list","Benchmarking","Center Specific","ECMO Run". What is the simplest method to do that in razor? Thank you in advance for any help.

alenan2013
  • 207
  • 3
  • 22

1 Answers1

2

In your view :

@{
   List<SelectListItem> listItems= new List<SelectListItem>();
   listItems.Add(new SelectListItem{Text = "Patient list", Value = "Patient list"});
   listItems.Add(new SelectListItem{Text = "Benchmarking", Value = "Benchmarking"});
   listItems.Add(new SelectListItem{Text = "Center Specific",Value = "Center Specific"});
   listItems.Add(new SelectListItem{Text = "ECMO Run",Value = "ECMO Run"});
}

@Html.DropDownListFor(model => model.MySelectedItem, listItems, "-- Select --")

in your controller I assume you have a model object which has a property called MySelectedItem. So in controller the action method code would be like this :

public ActionResult MyAction(...)
{
   ...
   model.MySelectedItem="Benchmarking";// just as example
   return View(model);
}
akardon
  • 43,164
  • 4
  • 34
  • 42
  • thank you very much. Could you please explain how to implement an event like "SelectedIndexChange" in the DropDownList? – alenan2013 Jun 23 '16 at 00:25
  • 1
    You're welcome. you can simply give an Id to your control with : `@Html.DropDownListFor(model => model.MySelectedItem, listItems, "-- Select --", new {@id='myDropdown'})` and add this javascript to your view `$('select#myDropdown').change(function() {/* your javascript code */});` and throw that javascript code you can do whatever you want. BTW I assumed you're using JQuery. – akardon Jun 23 '16 at 01:25