MVC3 drop-down does not select the selected item

I have a C # .Net MVC3 web application. I use Drop Down lists everywhere and have success. However, there are two problems that I have encountered. The only difference is that I create SelectListson the fly in code, and not using Lookup tables. I use lookup tables for all the rest of Drop Downs. When I QuickWatch SelectListsin code, the correct item has a property value Selectedset to true. However, when the page loads, the item with the property is Selectednot displayed. The first element. Any ideas? This is one of those crazy. I tried both ways below. In both cases, ViewBag.DateToYear and SelectList DateToYear have the correct values, and the Selected properties are set

1)

//controller

        IList<string> dateToYear = new List<string>();
        for (int i = 0; i < numberYears; i++)
        {
            dateToYear.Add(DateTime.Now.AddYears(i).Year.ToString());
        }
        ViewBag.DateToYear = new SelectList(dateToYear,"2014")

// view

        @Html.DropDownList("DateFromYear", (SelectList)ViewBag.DateToYear )

2) // controller ALSO as above

// view

List<SelectListItem> DateToYear = new List<SelectListItem>();
foreach (var m in ViewBag.DateToYear)
{
    DateToYear.Add(new SelectListItem { Selected = @m.Selected, Value = @m.Text, Text = @m.Text });
} 

@Html.DropDownList("DateFromYear", DateToYear)
+5
source share
3 answers

Not sure if this is the case, but I had a problem with dropdownbox that were not selected a few days ago.

My problem: I have @model.Options, and I created @html.dropdownlist("Options", @model.Options, [...]). However, since they have the same name, this somehow contradicted. When I used @html.dropdownlist("anythingElse", @model.Options, [...]), it worked fine.

When I QuickWatched return View(model), the selected options seemed to be configured correctly, so it took a while to figure this out. Maybe you have the same problem?

+5
source

, SelectList , . . SelctedItem, , GetEnumerator() ( Mvc ). Mvc SelectfListItems.

SelectList ctor SelectListItem [], Text-Name, Value-Name SelectedValue. , SelectedValue VALUE SelectListItem, , SelectListItem! :

?

:

//

ViewBag.DateToYear = new SelectList(new[]  
{ 
 new SelectListItem { Text = "10", Value = "10" }, 
 new SelectListItem { Text = "15", Value = "15" } 
 new SelectListItem { Text = "25", Value = "25" }, 
 new SelectListItem { Text = "50", Value = "50" }, 
 new SelectListItem { Text = "100", Value = "100" }, 
 new SelectListItem { Text = "1000", Value = "1000" }, 
}, "SomeText", "Value", "15");

.

+6

, , , , . ...

0

All Articles