开发者

MVC3 Razor - ListBox pre-select not working

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?


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")
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜