簡體   English   中英

如何使用模型中的數據定義List,然后與lambda表達式一起使用以獲取所有元素

[英]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模型,但在此示例中,我假設它具有名為IdName屬性,這是DropDownList綁定到的屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM