如何在displaytemplate中显示下拉列表的选定文本而非选定值?

时间:2012-09-24 18:16:24

标签: asp.net-mvc asp.net-mvc-3 razor

所以我在displaytemplate中有这段代码:

@Html.DropDownListFor(blah => blah.InputtedData, ddv)

我得到一个实际的下拉列表。我试过这段代码:

@Html.DisplayFor(blah => blah.InputtedData, ddv)

我得到1(头号),选中的值。但我想显示所选文本Yes。那么如何在displaytemplate中的下拉列表中显示selectedtext而不是selectedvalue呢?

按要求:

namespace TESTMVC.ViewModels
{
    public class CtrlInputDataModel
    {
        public CtrlTypeModel RowCtrl { get; set; }
        public long InputtedDataID { get; set; }
        public string InputtedData { get; set; }
        public DateTime InputtedDate { get; set; }

        public CtrlInputDataModel()
        {

        }

        public CtrlInputDataModel (CtrlTypeModel newRowCtrl, long newInputtedDataID, string newInputtedData, DateTime newInputtedDate)
        {
            RowCtrl = newRowCtrl;
            InputtedDataID = newInputtedDataID;
            InputtedData = newInputtedData;
            InputtedDate = newInputtedDate;
        }
    }
}

ddv基于的ViewModel:

namespace TESTMVC.ViewModels
{
    public class DefaultValueModel
    {
        public string Label { get; set; }
        public string Value { get; set; }

        public DefaultValueModel()
        {

        }

        public DefaultValueModel(string newLabel, string newValue)
        {
            Label = newLabel;
            Value = newValue;
        }
    }
}

1 个答案:

答案 0 :(得分:4)

使用内置的Html.DisplayFor无法做到这一点。但是,您可以创建自定义displaytemplate,例如/Views/Shared/DisplayTemplates/DropdownListTest.cshtml您可以根据属性从下拉列表值中手动选择文本:

@model string
@((IEnumerable<SelectListItem>)ViewData["ddv"])
    .Where(s => Model == s.Value)
    .Select(s => s.Text).SingleOrDefault()

然后您可以使用以下(稍微复杂的)语法:

@Html.DisplayFor(blah => blah.InputtedData, 
     "DropdownListTest", //template name
     new { ddv = ddv } // aditional view data: the property name needs to be ddv
})

但如果不打算重复使用此功能,只需内联逻辑并使用此代替Html.DisplayFor

@ddv.Where(s => s.Value == Model.InputtedData)
    .Select(s => s.Text).SingleOrDefault()