以下に説明する2つの方法のいずれかを使用してみます。
1.カスタムエディタテンプレートを使用する
MyModel
配列をドロップダウンリストとプロパティとして表示し、 <option>要素のデータ属性として表示するSomeProperty1
とします。SomeProperty2
public class MyModel
{
public int Id { get; set; }
public string Value { get; set; }
public string SomeProperty1 { get; set; }
public string SomeProperty2 { get; set; }
}
// CustomSelectList.cshtml (editor template)
@model MyModel[]
<select>
@foreach (var i in Model)
{
<option name="@i.Id" data-attr-1="@i.SomeProperty1" data-attr-2="@i.SomeProperty2">@i.Value</option>
}
</select>
2.テンプレート化されたかみそりのデリゲートを使用する
public static class RazorExtensions
{
public static HelperResult List<T>(this IEnumerable<T> items,
Func<T, HelperResult> template)
{
return new HelperResult(writer =>
{
foreach (var item in items)
{
template(item).WriteTo(writer);
}
});
}
}
// Model is MyModel[]
<select>
@Model.List(@<option name="@item.Id" data-attr-1="@item.SomeProperty1" data-attr-2="@item.SomeProperty2">@item.Value</option>)
</select>