4

我有一个像这样的下拉列表:

@Html.DropDownList("DeliveryOptions",
(IEnumerable<SelectListItem>)ViewData["DeliveryOptions"])

这从控制器操作中获取数据,如下所示:

var options = context.DeliveryTypes.Where(x => x.EnquiryID == enqId);
ViewData["DeliveryOptions"] = new SelectList(options, "DeliveryTypeId", 
"CODE" + " - " + "DeliveryPrice");

我想让我的下拉列表CODE + DeliveryPrice在其文本字段中显示,例如:'TNTAM - 17.54' 但我收到以下错误:

DataBinding: 'MyApp.Models.DeliveryTypes' does not contain a property 
with the name 'CODE - DeliveryPrice'.

我的 DeliveryType 模型如下所示:

[Key]
public int DeliveryTypeId { get; set; }
public string CODE { get; set; }
public decimal DeliveryPrice { get; set; }
4

1 回答 1

1

您可以使用匿名类型:

var options = context.DeliveryTypes
    .Where(x => x.EnquiryID == enqId)
    .Select(x => new { Value = x.DeliveryTypeId, Text = x.CODE + " - " + x.DeliveryPrice });

ViewData["DeliveryOptions"] = new SelectList(options, "Value", "Text");

或者创建一个CustomSelectListItem您可以重用的特定类,其中包含您可以在这种情况下重用的属性ValueText

于 2012-05-28T12:26:34.193 回答