多选列表框中的预选项目 (MVC3 Razor) [英] Preselect Items in Multiselect-Listbox (MVC3 Razor)

查看:25
本文介绍了多选列表框中的预选项目 (MVC3 Razor)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在列表框中预选项目时遇到问题.我正在使用带有 mvc 3 的 razor 视图引擎.我知道有一些帖子有同样的问题,但它们对我不起作用.

I have a problem with the preselection of Items in a listbox. I am using razor view engine with mvc 3. I know there are a few posts with the same issue but they don't work for me.

课堂代码:

public class Foo{
    private int _id;
    private string _name;

    public string Name{
       get{
           return _name;
       }

    public int Id {
       get{
           return _id;
       }

}

模型中的代码:

public class FooModel{

    private readonly IList<Foo> _selectedFoos;
    private readonly IList<Foo> _allFoos;

    public IList<Foo> SelectedFoos{
         get{ return _selectedFoos;}
    }

    public IList<Foo> AllFoos{
         get{ return _allFoos;}
    }

}

cshtml 中的代码:

Code in cshtml:

 @Html.ListBoxFor(model => model.Flatschels, 
        Model.AllFlatschels.Select(fl => new SelectListItem {
             Text = fl.Name,
             Value = fl.Id.ToString(),
             Selected = Model.Flatschels.Any(y => y.Id == fl.Id)
   }), new {Multiple = "multiple"}) 

我尝试了很多其他的东西,但没有任何效果.希望有人能帮忙.

I tried lots of other things but nothing worked. Hope someone can help.

推荐答案

我真的无法解释原因,但我设法让它发挥作用.其中任何一个都有效:

I can't really explain why, but I managed to get it working. Either of these worked:

@Html.ListBoxFor(m => m.SelectedFoos,
            new MultiSelectList(Model.AllFoos, "ID", "Name"), new {Multiple = "multiple"}) 

@Html.ListBoxFor(m => m.SelectedFoos, Model.AllFoos
            .Select(f => new SelectListItem { Text = f.Name, Value = f.ID }),
                new {Multiple = "multiple"}) 

问题似乎是 SelectListItem 上的 Selected 属性被忽略,而是调用了 ToString()(!) 方法,因此如果您需要将其添加到您的 Foo 类:

The problem seems to be that the Selected property on SelectListItem is ignored, and instead the ToString()(!) method is being called, so if you need to add this to your Foo class:

public override string ToString()
{
    return this.ID;
}

我猜这与能够跨请求持久化有关(这将被扁平化为要通过网络传递的字符串),但这有点令人困惑!

I'm guessing it has something to do with being able to persist across requests (which will be flattened to strings to be passed over the wire), but it's a bit confusing!

这篇关于多选列表框中的预选项目 (MVC3 Razor)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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