在多选,列表框preSELECT项目(MVC3剃刀) [英] Preselect Items in Multiselect-Listbox (MVC3 Razor)

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

问题描述

我有一个列表框项目的preselection一个问题。 我使用的剃刀视图引擎与MVC 3,我知道有几个职位有相同的问题,但他们不为我工作。

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.

code。在类别:

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

    public string Name{
       get{
           return _name;
       }

    public int Id {
       get{
           return _id;
       }

}

code的型号:

Code in Model:

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

}

code在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选定的属性被忽略,而不是的ToString()(!)方法被调用,因此,如果您需要添加这对你的类:

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!

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

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