2012-06-21 250 views
5

Cuando se publica la espalda me sale el siguiente error:valor por defecto Ajuste de un Html.DropDownList()

The ViewData item that has the key 'ClosingDateDay' is of type 'System.Int32' but must be of type 'IEnumerable'. Any ideas?

Aquí está mi controlador:

CompetitionEditViewModel viewModel = new CompetitionEditViewModel 
{ 
    ClosingDate = competition.CloseDate, 
    Description = competition.Description, 
    DescriptionHeading = competition.DescriptionHeading, 
    ImageAssetId = competition.ImageAssetId, 
    IsActive = competition.IsActive, 
    MainHeading = competition.MainHeading, 
    TermsAndConditions = competition.TermsAndConditions, 
    UrlSlug = competition.UrlSlug 
}; 

viewModel.ClosingDateMonthOptions = new List<SelectListItem>(); 
for (int i = 1; i <= 12; i++) 
{ 
    string monthName = new DateTime(2000, i, 1).ToString("MMMM"); 
    ((List<SelectListItem>)viewModel.ClosingDateMonthOptions).Add(new SelectListItem { Text = monthName, Value = i.ToString() }); 
} 

viewModel.ClosingDateDayOptions = new List<SelectListItem>(); 
for (int i = 1; i <= 31; i++) 
{ 
    ((List<SelectListItem>)viewModel.ClosingDateDayOptions).Add(new SelectListItem { Text = i.ToString().PadLeft(2, '0'), Value = i.ToString() }); 
} 

viewModel.ClosingDateYearOptions = new List<SelectListItem>(); 
for (int i = DateTime.Now.Year; i <= DateTime.Now.Year + 3; i++) 
{ 
    ((List<SelectListItem>)viewModel.ClosingDateYearOptions).Add(new SelectListItem { Text = i.ToString(), Value = i.ToString() }); 
} 

Y aquí está mi punto de vista:

@Html.Uber().LabelFor(x => x.ClosingDateDay, new { @class = "access" }) 
@Html.DropDownListFor(x => x.ClosingDateDay, Model.ClosingDateDayOptions, Model.ClosingDateDay) 

@Html.Uber().LabelFor(x => x.ClosingDateMonth, new { @class = "access" }) 
@Html.DropDownListFor(x => x.ClosingDateMonth, Model.ClosingDateMonthOptions, Model.ClosingDateMonth) 

@Html.Uber().LabelFor(x => x.ClosingDateYear, new { @class = "access" }) 
@Html.DropDownListFor(x => x.ClosingDateYear, Model.ClosingDateYearOptions, Model.ClosingDateYear) 
+0

Es el segundo fragmento de código falta un '.'? Supongo que en su opinión tiene 'Model.ClosingDate.Day' y así sucesivamente como el último parámetro de los menús desplegables? – Franky

+0

@Franky No, no lo es. Pero definitivamente me acabas de ayudar a resolver el problema jaja. Gracias. – ediblecode

+0

Feliz de ayudar, pero ¿le importa explicarlo? – Franky

Respuesta

9

Al construir sus clases SelectListItem, establezca la propiedad Selected en true para el elemento que desea seleccionar inicialmente.

+0

Con la sobrecarga que está usando, él suministra el valor seleccionado como el tercer parámetro. – Franky

+3

No existe tal sobrecarga para aceptar el "valor predeterminado" para un menú desplegable. Como @tarnbridge dijo, uno de los elementos en 'List ' tiene que tener '.selected = true '. – Tohid

+0

@Tohid La tercera sobrecarga en 'Html.DropDownFor()' es la otra forma de establecer el valor predeterminado. De esto es de lo que habla @Franky – ediblecode

1

Lo que hice en uno de mis proyectos y estaba un poco útil, fue el desarrollo de más de 2 sobrecarga para
DropDownListFor que aceptan selectedValue.

namespace MyMvcApplication.Helpers 
{ 
    public static class ExtensionMethods 
    { 
     public static MvcHtmlString DropDownListFor<TModel, TProperty> 
          (this HtmlHelper<TModel> helper, 
           Expression<Func<TModel, TProperty>> expression, 
           string selectedValue, 
           IEnumerable<SelectListItem> selectList, 
           string optionLabel, 
           object htmlAttributes) 
     { 
      if (string.IsNullOrEmpty(selectedValue)) 
       selectedValue = string.Empty; 
      if (selectList != null) 
      { 
       foreach (SelectListItem sli in selectList) 
       { 
        if (sli.Value.ToLower().Trim() == selectedValue.ToLower().Trim()) 
        { 
         sli.Selected = true; 
         break; 
        } 
       } 
      } 
      else 
      { 
       selectList = new List<SelectListItem>() 
            { new SelectListItem() 
              { Text = "", Value = "", Selected = true } 
            }; 
      } 
      return helper.DropDownListFor(expression, selectList, optionLabel, htmlAttributes); 
     } 


     public static MvcHtmlString DropDownListFor<TModel, TProperty> 
          (this HtmlHelper<TModel> helper, 
           Expression<Func<TModel, TProperty>> expression, 
           string selectedValue, 
           IEnumerable<SelectListItem> selectList, 
           string optionLabel, 
           IDictionary<string, object> htmlAttributes) 
     { 
      if (string.IsNullOrEmpty(selectedValue)) 
       selectedValue = string.Empty; 
      if (selectList != null) 
      { 
       foreach (SelectListItem sli in selectList) 
       { 
        if (sli.Value.ToLower().Trim() == selectedValue.ToLower().Trim()) 
        { 
         sli.Selected = true; 
         break; 
        } 
       } 
      } 
      else 
      { 
       selectList = new List<SelectListItem>() 
            { new SelectListItem() 
              { Text = "", Value = "", Selected = true } 
            }; 
      } 
      return helper.DropDownListFor(expression, selectList, optionLabel, htmlAttributes); 
     } 

    } 
} 

Así, en Vistas, me puede pasar una cadena como SelectedValue a DropDownListFor, como:

@using MyMvcApplication.Helpers 

@Html.DropDownListFor(model => model.MyData, 
           "Default Value for DropDownList", //Or Model.MySelectedValue 
           Model.MySelectList, null, mull) 
Cuestiones relacionadas