0

我想做的是用模型中的数据填充列表并设置为查看并在视图中显示使用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)
}
4

1 回答 1

1

您的 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 所绑定的。

于 2013-03-03T09:30:10.013 回答