您的 C# 语法无效,但您走在正确的轨道上。
定义模型:
public class CategoriesModel
{
public int Id { get; set }
public string CategoryName { get; set }
public List<CategoryName> CategoryNames { get; set; }
}
控制器:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new CategoriesModel();
model.CategoryNames = GetCategoryNames();
return View(model);
}
private List<CategoryName> GetCategoryNames()
{
// TODO: you could obviously fetch your categories from your DAL
// instead of hardcoding them as shown in this example
var categories = new List<CategoryName>();
categories.Add(new CategoryName { Id = 1, Name = "category 1" });
categories.Add(new CategoryName { Id = 2, Name = "category 2" });
categories.Add(new CategoryName { Id = 3, Name = "category 3" });
return categories;
}
}
最后是模型的强类型视图:
@model CategoriesModel
@using (Html.BeginForm())
{
@Html.DropDownListFor(
x => x.CategoryName,
new SelectList(Model.CategoryName, "Id", "Name")
)
<button type="submit"> OK</button>
}
您尚未展示您的CategoryName
模型,但在此示例中,我假设它具有已调用的属性Id
,并且Name
是 DropDownList 所绑定的。