简体   繁体   中英

How to define List with data from model and then use with lambda expression to get all elements

What i trying to do is to fill list with names with data from model and set to View and show in view With dropDownListFor ...is my logic a right ...and what i should do else

Model :

public class Categories{
public int id {get;set}
public string categoryName{get;set}
    public List<CategoryName> catNames {get;set;} //or IEnumerable<>
}

controller:

public ActionResult getSomething(){
public List<CategoryName>   list = new List<CategoryName>() ;
public List<CategoryName> names= list.FindAll(x=>x.categoryName);
return View(names)
}

You have invalid C# syntax but you are on the right track.

Define a model:

public class CategoriesModel
{
    public int Id { get; set }
    public string CategoryName { get; set }
    public List<CategoryName> CategoryNames { get; set; }
}

a controller:

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;
    }
}

and finally a strongly typed view to the model:

@model CategoriesModel
@using (Html.BeginForm())
{
    @Html.DropDownListFor(
        x => x.CategoryName, 
        new SelectList(Model.CategoryName, "Id", "Name")
    )
    <button type="submit"> OK</button>
}

You haven't shown your CategoryName model but in this example I am supposing that it has properties called Id and Name which is what the DropDownList is bound to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM