2017-12-08 4 views
2

C#/asp.net/mvc의 초보자로서 View의 Html.DropDownList에서 개체를 가져 오는 방법을 찾을 수 없습니다.리스트에서 객체를 얻는 방법 DropDownlistFor에 <typeObject>?

public ActionResult Index() { 
    MyViewModel mvm=new MyViewModel(); 
    mvm.ListOfSomething=(my code to populate the List); 
    return View(vm); 
} 

보기는 여기에 있습니다 : 내가 컨트롤러 내 목록 <>를 채울

public class Something { 
    public int Id {get;set;} 
    public string Name {get;set;} 
    public int AnotherProperty {get;set;} 
} 

:

public class MyViewModel { 
    public List<Something> ListOfSomething {get;set;} // A list of Somethings 
    public Something TheSomethingToGet {get;set;} // The object I want to get 
} 

은 "뭔가"개체가, 예를 들면 : 여기 내 뷰 모델입니다 :

@model Project.ViewModels.MyViewModel 
@Html.LabelFor(m => m.ListOfSomething) 
@Html.DropDownListFor(m => m.ListOfSomething, new SelectList(Model.ListOfSomething, "id", "name"), "-")<br/> 

그리고 결국, [HttpPost] 컨트롤러의 인덱스 :

[HttpPost] 
public ActionResult Index(MyViewModel mvm) { 
    /* Here, how could I get the "Something" object that 
     was selected in the dropdownlist and can be identified 
     by the "id" property ? 
    */ 

} 

나는 완전히 틀렸다? 감사

+0

'mvm.ListOfSomething.Where (o => o.Id == DropDownList.Selected.ID)'와 같은 것 같지만 dropdownlist.selected.id 부분은 확실하지 않습니다 .... – hellyale

답변

0

나의 이해에 당신이 무엇을해야하는지 예를 int, string 원시적 형의 경우, 함께 DropDownListFor 작품을 따르면되는 뷰 모델의 SelectedId 속성을 가지고 이드 당신이 끌어있을 것이라는 점을 사용하여 컨트롤러에서 다음, 그 게시 컨트롤러에서보기 모델의 컬렉션에서 선택한 항목.

당신은 그것을 좋아 시도 할 수 있습니다 :보기에

public class MyViewModel { 
    public List<Something> ListOfSomething {get;set;} // A list of Somethings 
    public int SelectedItem {get;set;} 
} 

지금을, 당신은해야 할 것 :

[HttpPost] 
public ActionResult Index(MyViewModel mvm) { 
    // use mvm.SelectedItem id to get the selected complete object from repository 
} 

: 당신의 액션 메소드에서 다음

@Html.DropDownListFor(m => m.SelectedItem, new SelectList(Model.ListOfSomething, "id", "name"), "-") 

과 잘하면 도움이 될 것입니다.

0

이제 컨트롤러에서 Something 개체를 인스턴스화 할 수 없다는 것을 알았습니다. id를 사용하여 목록의 해당 레코드 나 항목을 찾아서 사용하는 것이 제 일입니다. 감사합니다

관련 문제