使用ViewModel中的SelectList创建DropDownList

时间:2012-07-23 09:46:37

标签: c# asp.net-mvc-3 drop-down-menu

我一直在尝试使用SelectList类创建一个下拉列表。 我的意思是以下。

public class MyViewModel
{
    public int SelectedValue { get; set; }
    public IEnumerable<int> ValueList { get; set; }
}

有很多关于如何让它工作的例子,我有。我希望在视图模型中使用上述SelectList类。

public class MyViewModel
{
    public SelectList ValueList { get; set; }
}

我怀疑,这样做的好处是,当结果传递给控制器​​并且ModelState无效时,你可以return View(model)完成所有事情。 如果你拆分它,你将不得不再次获取项目列表,以某种方式设置所选的值。太不方便了!

为什么没有人在视图模型中使用SelectList?如果可能,我会感谢一个有效的例子:)

谢谢。

1 个答案:

答案 0 :(得分:0)

我的项目中有这样的场景。我正在使用MVC3,但我相信这会适用。

在我的ViewModel中,我有一个如下定义的属性:

        private List<SelectListItemWithAttributes> pLeadDispositions = null;
    public List<SelectListItemWithAttributes> LeadDispositions {
        get {
            var LeadDispositionItems = (
                from c in db.GetLeadDispositionList(1, 1000)
                where c.AccountTypeID == this.AccountTypeID
                select new SelectListItemWithAttributes() { Text = c.Title, Value = c.ID.ToString(), HtmlAttributes = new Dictionary<string, string> { { "data-callback", c.RequiresCallback.ToString().ToLower() } } } ).ToList()
            ;

            LeadDispositionItems.Insert(0, new SelectListItemWithAttributes() { Text = "-- Select --", Value = "", HtmlAttributes = new Dictionary<string, string> { { "data-callback", "false" } } });

            return LeadDispositionItems;
        }
    }

SelectListItemWithAttributes只是我正在使用的SelectListItem的子类,所以你可以用SelectListItem替换它并修改参数列表。 GetLeadDispositionList是一个存储过程,它从数据库中获取我需要的数据。

在我看来是这样的:

@Html.DropDownListWithItemAttributesFor(m => m.LeadDispositionID, Model.LeadDispositions) 

DropDownListWithItemAttributesFor是我用于项目的DropDownListFor的子类,所以只是替换DropDownListFor

我知道这不是你想要的,但也许它会让你指向正确的方向。

我希望这会有所帮助。

相关问题