2016-07-29 4 views
0

MVC에서.면도기의 람다에서 선택 목록 값을 표시 할 수 없습니다.

면도기에 dropDownList를 표시하려고 할 때이 오류 메시지가 나타납니다.

DataBinding : 'System.Int32'에 'BranchId'라는 이름의 속성이 없습니다. 내가 한 기록을 볼 수 있어요 시계 창에서

나는 모델 클래스의 SelectList에 대한 참조가없는 BranchIdBranchName 가 포함 된 데이터베이스에서 반환되고있다. Controller 클래스 Create.cshtml

@Html.DropDownList("Branch", new SelectList(ViewBag.Branch, "BranchID", "BranchName"), htmlAttributes: new { @class = "form-control" }) 

감사에서

var list = new SelectList(db.Branchs.Where(branches => !db.CompanyBranches 
    .Any(d => d.BranchId == branches.BranchId)) 
    .Select(branches => branches.BranchId).ToList(), 
    "BranchId", "BranchNumber"); 
ViewBag.Branch = new SelectList(list); 

에서

는 을 제안 내 CompanyBranchesController에서 람다 식을 변경

스티븐은 지금이다 var list = db.Branchs.Where (가지 =>! db.C ompanyBranches .Any (d => d.BranchId == branches.BranchId)) .Select (b => new {BranchId = b.BranchId, BranchName = b.BranchName}). ToList();

에 결과 :

드롭 다운리스트의 Create.cshtml는 @ Html.DropDownList (새 {@class = "폼 제어"} "분기"는 IEnumerable ViewBag.Branch, htmlAttributes 등) 인 드롭 다운리스트가 이다 {BranchId = 5, BranchNumber = Br0003}

나는 CompanyBranchController 목록 항목 = 새로운 목록에 추가하는 등 함께 연주 한(); foreach (목록에있는 var i) { SelectListItem s = new SelectListItem(); s.Text = i.BranchName.ToString(); s.Value = i.BranchId.ToString(); items.Add (s);

다른 면도기 표현을 시도 할뿐만 아니라 성공하지 못했습니다.

내가 잘못 가고있는 아이디어가 있습니까? 코드의이 부분에서

답변

1

봐 (selectList의 생성자)

Select(branches => branches.BranchId).ToList() 

당신은 branchId의 선택된다. 따라서 기본적으로 정수 목록을 SelectList 생성자에 전달합니다. 그러나 BranchId이 데이터 값 필드임을 지정합니다. 그러나 정수에는 그러한 속성이 없습니다.

그래서 당신은

Select(b => new { BranchId = b.BranchId, BranchNumber = b.BranchId).ToList() 

은 또한 당신이 ViewBag에 할당 할 때 또 다른 selectList의를 만들 필요가 없습니다 이러한 특성을 가진 annonymous 유형으로 선택을 변경해야합니다. 그래서 이것은 단순히 SelectListItem

var list= db.Branchs.Where(// Put your where clause here) 
      .Select(branches => new SelectListItem { Value = branches.BranchId.ToString(), 
             Text = branches.BranchId.ToString()}).ToList(); 
ViewBag.Branch = list; 
+0

감사합니다 – Paul

0

귀하의 코드 목록에 항목을 변환 할 수 있습니다,

@Html.DropDownList("Branch", ViewBag.Branch as IEnumerable<SelectListItem>, 
             htmlAttributes: new { @class = "form-control" }) 

또는 더 쉽게

ViewBag.Branch = list; 

하고보기에

충분 CompanyBranchContoller에서 추가 한 것을 제외하고는 정확했습니다.

목록 항목 = 새 목록(); foreach (목록에있는 var i) { SelectListItem s = new SelectListItem(); s.Text = i.BranchName.ToString(); s.Value = i.BranchId.ToString(); items.Add (s);
}

ViewBag.Branch = items; 새로운 {@class = "폼 컨트롤 :

그런 다음 Create.cshtml 클래스에서 나는 IEnumerable을, 당신이 @ Html.DropDownList ("지점 "을 제안 무엇을 htmlAttributes을 ViewBag.Branch을 드롭 다운 목록에 대한 참조를 변경 "}) 당신의 도움 스티븐

폴의 모든

답장을 보내 주셔서 감사합니다 스티븐위한

관련 문제