您可以采取的一种方法是将下拉列表值提取到它们自己的视图模型中。所以:
第 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
andtype
将根据您认为合适的方式来确定,并且是可选的。
希望这能给你一些启发。