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 に答える