2014-04-08 2 views
0

다음 코드를 가지고 양식을 제출하면 내 게시 작업에서 연락처 개체가 null로 표시됩니다. 뷰에서 DropDownListFor를 제거하면 Contact 개체에 예상 정보 (FirstName)가 포함됩니다. 왜? SelectList 값을 얻으려면 어떻게해야합니까?DropDownListFor SelectList가 HttpPost에 바인딩되지 않은 모델

내 클래스 :

public class ContactManager 
{  
    public Contact Contact { get; set; }  
    public SelectList SalutationList { get; set; } 
} 
public class Contact 
{ 
    public int Id{get;set;} 
    public string FirstName{get; set;} 
    public SalutationType SalutationType{get; set;} 
} 
public class SalutationType 
{  
    public int Id { get; set; } 
    public string Name { get; set; }  
} 

내보기 :

@model ViewModels.ContactManager 

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(true) 
    @Html.HiddenFor(model => model.Contact.Id) 
    @Html.DropDownListFor(model => model.Contact.SalutationType.Id, Model.SalutationList, "----", new { @class = "form-control" }) 
    @Html.EditorFor(model => model.Contact.FirstName) 
    <input type="submit" value="Save" /> 
} 

내 컨트롤러 :

public ActionResult Edit(int? id) 
{ 
    Contact contact = db.Contacts.FirstOrDefault(x => x.Id == id); 
    ContactManager cm = new ContactManager(); 
    cm.Contact = contact; 
    cm.SalutationList = new SelectList(db.SalutationTypes.Where(a => a.Active == true).ToList(), "Id", "Name"); 
    return View(cm); 
} 
[HttpPost] 
public ActionResult Edit(ContactManger cm) 
{ 
//cm at this point is null 
    var test = cm.Contact.FirstName; 
    return View(); 
} 

답변

0

당신은 사용하여 드롭 다운리스트를 전달합니다 ViewBag :

ViewBag.SalutationList = new SelectList(db.SalutationTypes.Where(a => a.Active == true).ToList(), "Id", "Name"); 
,

u는 당신의 편집보기 내에서이 목록을 호출하는 것보다 :

@Html.DropDownList("SalutationList",String.Empty) 
+0

왜 모델에 없습니까? 복잡한 모델의 일부로 전달되는 예제를 볼 수 있습니다. –

+0

또한 ViewModel 내의 올바른 위치에 값을 반환하지 않습니다. 즉 model.Contact.SalutationType.Id –

0

문제는 DefaultModelBinder이 다른 매개 변수 이름을 사용하는 경우 제대로 중첩 된 모델을 매핑 할 수 없을 것입니다. 동일한 매개 변수 이름을 모델 이름으로 사용해야합니다.

public ActionResult Edit(ContactManager contactManager) 

일반적으로 매핑 문제를 피하기 위해 항상 모델 이름을 매개 변수 이름으로 사용하십시오.

또한 제안 :

당신은 단지 매개 변수 모델 만 접촉 모델을 필요로하는 경우 ContactManager를 사용할 필요가 없습니다으로 Contact를 사용할 수 있습니다.

[HttpPost] 
public ActionResult Edit(Contact contact) 
{ 
    var test = contact.FirstName; 
    return View(); 
} 
관련 문제