![](/img/trans.png)
[英]How to get a inherited object member from a list with lambda expression
[英]How to define List with data from model and then use with lambda expression to get all elements
我想做的是用來自模型的數據用名稱填充列表,並設置為View並使用dropDownListFor在視圖中顯示...是我的邏輯,是正確的,而我應該做的其他事情
型號:
public class Categories{
public int id {get;set}
public string categoryName{get;set}
public List<CategoryName> catNames {get;set;} //or IEnumerable<>
}
控制器:
public ActionResult getSomething(){
public List<CategoryName> list = new List<CategoryName>() ;
public List<CategoryName> names= list.FindAll(x=>x.categoryName);
return View(names)
}
您的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綁定到的屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.