Asp mvc dropdown

I want to create a drop-down list for some attributes of my model class. I am working on an mvc.net application and I use a razor mechanism for viewing. Here is my class:

public class present { public DateTime jour { get; set; } public int entree_mat_h { get; set; } public int entree_mid_h { get; set; } public int sortie_mat_h { get; set; } public int sortie_mid_h { get; set; } public int entree_mat_m { get; set; } public int entree_mid_m { get; set; } public int sortie_mat_m { get; set; } public int sortie_mid_m { get; set; } public string mac { get; set; } public string ip { get; set; } } 

For example, I want to show a drop-down list with values ​​from 0 to 60 for each attribute, which is an integer. Does @ html.dropdownlistfor () work in this case?

+6
source share
3 answers

In your view, declare a list of possible values, in your case from 0 to 60

 @{ var values = new SelectList(Enumerable.Range(0, 60)); } 

Then you can use it in DropDownListFor helper

 @Html.DropDownListFor(m => m.entree_mat_h, values) @Html.DropDownListFor(m => m.entree_mid_h, values) .... 
+8
source

Yes, but you will need to pass a special selection list to it with the values ​​you wanted.

So you would do something like this:

  var list = new List<SelectListItem>(); for(int i=1; i < 61; i++) { list.Add(new SelectListItem{Text = i, Value = i}); } var sl = new SelectList(items, "Value", "Text"); 

Then you need to pass this to the model

Then in the view you will do the following:

  @Html.DropDownListFor(x => x.Quantity, @Model.Quantity) 

Or something like that.

Obviously, I used fake names, so you will need to configure it on your own model.

0
source

Use this extension method to create a drop-down list from the source (select all values ​​projecting onto the key and value). Example

 public static IEnumerable<SelectListItem> ToDropDown<TSource>(this IEnumerable<TSource> source, Func<TSource, string> keySelector, Func<TSource, string> elementSelector, Func<TSource,bool> selected) { if (source == null) { return new List<SelectListItem>(); } return source.Select(c => new SelectListItem { Value = keySelector(c), Text = elementSelector(c), Selected = selected(c) }).ToList(); } 

fill in your viewBag

 ViewBag.Languages = languageRepository().GetAll().ToList().ToDropDown(c => c.ID, c => c.Description, c => c.ID == "EN"); 

and finally a razor

  @Html.DropDownList("ddLanguages", (IEnumerable<SelectListItem>)ViewData.Languages, "Please Select") 
0
source

Source: https://habr.com/ru/post/923464/


All Articles