View of the model binding in MVC, very often use the drop-down box, so the drop-down box method to populate the data according to the data in the DataTable about this record
. 1 /// <Summary> 2 /// will turn into a drop-down box DataTable padding data List <SelectListItem> type . 3 /// </ Summary> . 4 /// <param name = "dt"> Data DataTable </ param > . 5 /// <param name = "keyColumnName"> display text column </ param> . 6 /// <param name = "valueColumnName"> select the value column </ param> . 7 /// <param name = "Please has select "> whether select </ param> . 8 /// <param name =" choose has text "> select the default text select = = </ param> 9 /// <param name="defaultValue">The default value of the drop down box </ param> 10 /// <Returns> </ Returns> . 11 public static List <SelectListItem> bindValues (the DataTable dt, String keyColumnName, String valueColumnName, BOOL has select = to false , String has select = the Text "" , String defaultValue = "" ) 12 is { 13 is List <SelectListItem> List = new new List <SelectListItem> (); 14 IF (has select) 15 { 16 SelectListItem item = new SelectListItem() { Text = has请选择Text == "" ? “=请选择=” : has请选择Text, Value = "" }; 17 list.Add(item); 18 } 19 20 21 if (dt.Rows.Count == 0) 22 return list; 23 List<Tuple<string, string>> valueList = DataTableToList(dt, keyColumnName, valueColumnName); 24 foreach (var item in valueList) 25 { 26 if (defaultValue != “” && defaultValue.Contains(item.Item1)) 27 list.Add(new SelectListItem() { Text = item.Item2, Value = item.Item1, Selected = true }); 28 else 29 list.Add(new SelectListItem() { Text = item.Item2, Value = item.Item1, Selected = false }); 30 } 31 return list; 32 }
This method is specified DataTable multiple columns of data as a text display, select a listed value, then a List of items to be stored according to the tuple Tuple. Tuple is C # 7.0 new out, are interested you can find out.
. 1 /// <Summary> 2 /// will turn into DataTable List . 3 /// </ Summary> . 4 /// <param name = "Table"> to turn DataTable </ param> . 5 /// <param name = "keyColumnName"> Specifies the text display column </ param> . 6 /// <param name = "valueColumnName"> specified value selected column </ param> . 7 /// <Returns> </ Returns> . 8 public static List < tuple < String , String >> DataTableToList (the DataTable Table, String keyColumnName,string valueColumnName) 9 { 10 List<Tuple<string, string>> list = new List<Tuple<string, string>>(); 11 if (table.Rows.Count == 0) 12 return null; 13 for (int i = 0; i < table.Rows.Count; i++) 14 { 15 list.Add(new Tuple<string, string>(table.Rows[i][keyColumnName].ToString(), table.Rows[i][valueColumnName].ToString())); 16 } 17 return list; 18 }