MVC3剃刀-ListBox预选无法正常工作 [英] MVC3 Razor - ListBox pre-select not working

查看:66
本文介绍了MVC3剃刀-ListBox预选无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在生成具有预选值的ListBox,如下所示.问题是当我选择其键串长度大于1的项目时,列表框选择了错误的项目.这是这种情况,

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 ;
}

在结果中,选择了具有值A,B和C的HTML项.没有选择BAYI和BC.这是什么问题?有什么主意吗?

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:

型号:

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" },
            };
        }
    }
}

控制器:

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

查看:

@model MyViewModel

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

这篇关于MVC3剃刀-ListBox预选无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆