MVC3 Razor - ListBox pre-select not working

2019-07-15 14:46发布

问题:

I'm generating a ListBox with preselected values as shown below . Problem is when i select an item that its keys string length is greater than 1 , listbox selects wrong items. Here is the situation ,

public static System.Web.Mvc.MultiSelectList CreateListBox()
{
    List<KeyValuePair<string, string>> alanList = new List<KeyValuePair<string, string>>();
            alanList.Add(new KeyValuePair<string, string>("A", "A"));
            alanList.Add(new KeyValuePair<string, string>("B", "B"));
            alanList.Add(new KeyValuePair<string, string>("BC", "BC"));
            alanList.Add(new KeyValuePair<string, string>("C", "C"));
            alanList.Add(new KeyValuePair<string, string>("D", "D"));
            alanList.Add(new KeyValuePair<string, string>("BAYI", "BAYI"));

            List<string> vals = new List<string>();
            vals.Add("BAYI");
            vals.Add("BC");
            System.Web.Mvc.MultiSelectList ret = new System.Web.Mvc.MultiSelectList(alanList, "Key", "Value", vals);

            return ret ;
}

In the result HTML items with values A,B and C are selected . BAYI and BC is not selected.What is the problem ? Any idea?

回答1:

The following works great for me and I would recommend it to you:

Model:

public class MyViewModel
{
    public IEnumerable<string> SelectedItemIds { get; set; }

    public IEnumerable<SelectListItem> Items 
    {
        get
        {
            return new[]
            {
                new SelectListItem { Value = "A", Text = "A" },
                new SelectListItem { Value = "B", Text = "B" },
                new SelectListItem { Value = "BC", Text = "BC" },
                new SelectListItem { Value = "C", Text = "C" },
                new SelectListItem { Value = "D", Text = "D" },
                new SelectListItem { Value = "BAYI", Text = "BAYI" },
            };
        }
    }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            SelectedItemIds = new[] { "BAYI", "BC" }
        };
        return View(model);
    }
}

View:

@model MyViewModel

@Html.ListBoxFor(
    x => x.SelectedItemIds, 
    new SelectList(Model.Items, "Value", "Text")
)