2013-03-03 1 views
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) 
} 

답변

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

및 모델에 강력한 형식의보기 : 당신은 당신의 CategoryName 모델을 표시하지 않은

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

하지만이 예제에서는 Id 및이라는 속성이 있다고 가정합니다.이는 DropDownList가 바인딩 된 것입니다.

+0

@ user2026573, StackOverflow는 영어로 말하는 웹 사이트이므로 영어로 작성하십시오. 데이터베이스에서 카테고리를 채우려면 내 대답에 표시된 값을 하드 코딩하는 대신 쿼리 할 수 ​​있습니다. 예를 들어 Entity Framework를 사용하고 있고 이미 DbContext를 가지고 있다면 그것으로부터 카테고리 이름을 직접 가져올 수 있습니다 :'model.CategoryNames = db.CategoryNames.ToList();' –

관련 문제