DropDownList如何选择默认值 [英] DropDownList how select default value

查看:149
本文介绍了DropDownList如何选择默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面上有很多DropDownLists

I have many DropDownLists on page

class BigViewModel
{
    public List<SmallViewModel> SmallVM {get;set;}
    public List<SelectListItem> Items {get;set;}
    //some other properties
}
class SmallViewModel
{
    public string ItemId {get;set;}
    //some other properties
}

<table>
    @for( var i = 0;i<Model.SmallVM.Count();i++)
    {
        <tr>
            <td>
                @Html.DropdownListFor(m=> m.SmallVM.ItemId, Model.Items)
            </td>        
        </tr>       
    }
//display other properties
</table>

在控制器中

bigViewModel.Items = List<SelectListItem>
{
    new SelectListItem{Value = "1", Text = "aaa"},
    new SelectListItem{Value = "2", Text = "bbb"},
    new SelectListItem{Value = "3", Text = "ccc"},
}
bigViewModel.SmallVM = new List<SmallViewModel>
{
    new SmallViewModel{ItemId = 3},
    new SmallViewModel{ItemId = 2},
}

在控制器中,我为每个SmallVM设置了差异ItemId,每个DropDownList使用相同的Items集合.我想为每个DropDownList设置来自SmallViewModel的默认值.例如,在这种情况下,有两个DropDownLists第一个应显示默认文本"ccc",第二个应显示"bbb".

In controller I set diffrent ItemId for every SmallVM and each DropDownList uses the same Items collection. I want to set default Value from SmallViewModel for each DropDownList. For example in this case there are two DropDownLists first should display default text "ccc" and second "bbb".

我应该为每个SmallViewModel放置不同的List<SelectedListItem>并将它们设置为Selected属性,还是有其他方法?

Should I put diffrent List<SelectedListItem> for every SmallViewModel and set them Selected property or there is other way?

推荐答案

已报告此行为是CodePlex上的错误,但尚未修复.在for循环中使用DropDownListFor()不能正确绑定,尽管该属性的值总是选择第一个选项.为了使DropDownListFor()在使用集合时正常工作,您需要为模型使用EditorTemplate.

This behavior has been reported as a bug on CodePlex but not yet fixed. Using DropDownListFor() in a for loop does not bind correctly and the first option is always selected despite the value of the property. In order for DropDownListFor() to work correctly when using a collection, you need to use an EditorTemplate for the model.

/Views/Shared/EditorTemplates/SmallViewModel.cshtml

@model SmallViewModel
@Html.DropdownListFor(m => m.ItemId, (SelectList)ViewData["Items"])

然后在主视图中

@model BigViewModel
@using(Html.BeginForm())
{
  // Pass the select list to the EditorTemplate as addtionalViewData
  @Html.EditorFor(m => m.SmallVM, new { Items = Model.Items })
  <input type="submit" />
}

您现在应该具有2个<select>控件,分别显示"ccc"和"bbb".

You should now have 2 <select> controls displaying "ccc" and "bbb" respectively.

这篇关于DropDownList如何选择默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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