2012-08-24 2 views
0

그래서 저는 StackOverflow를 많이 둘러보고 내 문제에 대한 좋은 해결책을 발견했습니다.DropDownList null 값, 사용 된 참조

MVC3 DropDownListFor - a simple example?이 작업은 저에게해야합니다. 하지만 null 값을 반환했습니다 ... 어떻게 든이 도움을받을 수 있도록이 문제를 해결하는 방법을 모릅니다. StateID = -1 어떤 이유로 널은 출력 만들어 내

모델 AccountModel.cs

... 
public string Address { get; set; } 
public string City { get; set; } 

public class StateList 
{ 
    public int StateID { get; set; } 
    public string Value { get; set; } 
} 

public IEnumerable<StateList> StateListOptions = new List<StateList> 
{ 
    //new StateList { StateID = -1, Value = "Select State" }, 
    new StateList { StateID = 0, Value = "NY" }, 
    new StateList { StateID = 1, Value = "PO" } 
}; 

public string State { get; set; } 

public string Zip { get; set; } 
... 

Register.cshtml

@Html.DropDownListFor(m => m.State, new SelectList(Model.StateListOptions, "StateID", "Value", Model.StateListOptions.First().StateID)) 

나는 어쩌면 생각 ...하지만 그것을하지 않았다 , 당신은 그것이 여기에 주석 처리 된 것을 볼 수 있습니다. 내가 뭘 잘못 했니?!

가져 오기 작업

public ActionResult Register() 
{ 
    ViewData["PasswordLength"] = MembershipService.MinPasswordLength; 

    return View(); 
} 
+0

GET 조치는 어떻게 생겼습니까? – Shyju

+0

문제의 조치를 추가했습니다. – rexdefuror

답변

3

하면 모델/뷰 모델의 객체를 생성하고 그 볼을 보낼 수 있습니다.

public ActionResult Register() 
{  
    AccountModel vm=new AccountModel(); 

    //Not sure Why you use ViewData here.Better make it as a property 
    // of your AccountModel class and pass it. 
    ViewData["PasswordLength"] = MembershipService.MinPasswordLength; 

    return View(vm); 
} 

는 이제보기 강하게
@model AccountModel 
@using(Html.BeginForm()) 
{ 
    //Other form elements also 
    @Html.DropDownListFor(m => m.State, new SelectList(Model.StateListOptions, 
               "StateID", "Value")"Select") 
    <input type="submit" /> 

} 

, 당신은 State 속성 값을 확인할 수 POST에서 선택한 국가를 얻기 위해이 모델 당신의 Register.cshtml보기에 따라서

에 입력해야합니다.

[HttpPost] 
public ActionResult Register(AccountModel model) 
{ 
    if(ModelState.IsValid) 
    { 
     // Check for Model.State property value here for selected state 
     // Save and Redirect (PRG Pattern) 
    } 
    return View(model); 
} 
+0

그래, 내 모델의 객체를 추가했는데 성공했다. 하지만'Value' 대신'StateID'를 저장합니다. 그것을 고치는 방법? : S – rexdefuror

+0

@ user1407758 :보기에서 Html.DropDownListFor 호출에서 StateID와 Value의 순서를 바꾸십시오. (값이 먼저 와야 함) – Shyju

+0

실제로 생각한 것처럼 그렇게 생각했지만 간단하게 보였습니다 ... – rexdefuror