取ることができるアプローチは、ドロップダウン リストの値を独自のビューモデルに抽出することです。そう:
ステップ 1:ItemsViewModel
ドロップダウン リスト項目をカプセル化するビュー モデル ( ) を作成します。
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Models
{
public class DropDownListItem
{
public string Text { get; set; }
public string Value { get; set; }
}
public class ItemsViewModel
{
private readonly List<DropDownListItem> _items;
// The selected item:
public string SelectedItem { get; set; }
// The items:
public IEnumerable<SelectListItem> Items
{
get
{
var allItems = _items.Select(i => new SelectListItem
{
Value = i.Value,
Text = i.Text
});
return DefaultItem.Concat(allItems);
}
}
// Default item (i.e. the "select" text) if none selected
public IEnumerable<SelectListItem> DefaultItem
{
get
{
return Enumerable.Repeat(new SelectListItem
{
Value = "-1",
Text = "Select an item"
}, count: 1);
}
}
public ItemsViewModel()
{
}
// Constructor taking in items from service and selected item string:
public ItemsViewModel(List<DropDownListItem> items, string selected)
{
_items = items;
SelectedItem = selected;
}
}
}
手順 2:にバインドする Views フォルダーに部分ビューを作成しますItemsViewModel
。
@model Models.ItemsViewModel
@Html.DropDownListFor(m => m.SelectedItem, Model.Items)
ステップ 3:適切なコントローラー (HomeController など) に、サービスからデータをプルする子アクション、ビュー モデル、および部分ビューを一緒に配置します。
[ChildActionOnly]
public ActionResult DropDownList(string type, string selected)
{
// If you need to call different services based on the type (e.g. Country), then pass through "type" and base the call on that
var items = new ItemsViewModel(
(from g in _service.getTitles() select new DropDownListItem { Text = g.Text, Value = g.Value }).ToList(),
selected);
return PartialView("DropDownPartial", items);
}
ステップ 4:このコード行を、ドロップダウン リストが必要なビューにドロップします。
@Html.Action("DropDownList", "Home", new { selected = "2", type = "country" })
selected
およびtype
は、適切と思われる方法を決定する必要があり、オプションであることに注意してください。
うまくいけば、これはあなたにいくつかのインスピレーションを与えます.