2014-02-10 2 views
0

작동하지 않는 드롭 다운 목록을 얻으려고하지만 그 기능이 작동하지 않습니다. 이 응용 프로그램은 주로 축제와 함께 축제를 추가 할 수있는 축제 기반 응용 프로그램입니다. 나는 점점 오전 오류가 라인에 :드롭 다운 목록 MVC 4 오류

유형 키 '마을'이 '는 IEnumerable'의 어떤을 ViewData 항목이 없습니다 :

@Html.DropDownList("towns", (IEnumerable<SelectListItem>)ViewData["Town"], new{@class = "form-control", @style="width:250px" }) 

이 내가 얻을 오류입니다.

Create.cshtml

<div class="form-group"> 
@Html.LabelFor(model => model.FestivalTown, new { @class = "control-label col-md-2" })  
<div class="col-md-10"> 
@Html.DropDownList("towns", (IEnumerable<SelectListItem>)ViewData["Town"], new{@class = "form-control", @style="width:250px" }) 
@Html.ValidationMessageFor(model => model.FestivalTown) 
</div> 
@*@Html.Partial("ddlFestivalCounty");*@ 
</div> 

Controller.cshtml

//Get 
List<SelectListItem> Towns = new List<SelectListItem>(); 
Towns.Add(new SelectListItem { Text = "Please select your Town", Value = "SelectTown" }); 
var towns = (from t in db.Towns select t).ToArray(); 
for (int i = 0; i < towns.Length; i++) 
{ 
Towns.Add(new SelectListItem 
{ 
Text = towns[i].Name, 
Value = towns[i].Name.ToString(), 
Selected = (towns[i].ID == 0) 
}); 
} 

ViewData["Town"] = Towns; 

//Post 
festival.FestivalTown.Town = collection["Town"]; 

Model.cs

나는이 오류가 발생 의심
public class Festival 
{ 
    public int FestivalId { get; set; } 

    [Required] 
    [Display(Name = "Festival Name"), StringLength(100)] 
    public string FestivalName { get; set; } 

    [Required] 
    [Display(Name = "Start Date"), DataType(DataType.Date)] 
    public DateTime StartDate { get; set; } 

    [Required] 
    [Display(Name = "End Date"), DataType(DataType.Date)] 
    public DateTime EndDate { get; set; } 

    [Required] 
    [Display(Name = "County")] 
    public virtual County FestivalCounty { get; set; } 

    [Display(Name = "Festival Location")] 
    public DbGeography Location { get; set; } 

    [Required] 
    [Display(Name = "Town")] 
    public virtual Town FestivalTown { get; set; } 

    [Required] 
    [Display(Name = "Festival Type")] 
    public virtual FestivalType FType { get; set; } 

    public UserProfile UserId { get; set; } 
} 

    public class Town 
{ 
    public int ID { get; set; } 
    [Display(Name = "Town")] 
    public string Name { get; set; } 
} 

답변

1

당신이 [HttpPost] 행동 양식을 제출 때 양식을 렌더링 할 때가 아닙니다. 맞습니까? 그리고이 동작은 드롭 다운을 포함하는 동일한 뷰를 렌더링합니다. 그리고이 [HttpPost] 액션 안에서는 ViewData["Town"] 값을 HttpGet 액션에서와 같은 방식으로 채우는 것을 잊었습니까?

그래서 GET 작업에서와 같은 방식으로이 속성을 채 웁니다. [HttpPost] 작업에 양식을 제출하면 만 컨트롤러에 전송됩니다. 따라서 동일한 뷰를 다시 표시하려면 콜렉션 값을 다시 채워야합니다.이 뷰는 그 값을 ViewData["Town"]에서 바인드하려고하는 드롭 다운을 렌더링하기 때문입니다.

그리고 여기에 내가 코드의 관점에서 의미있는 작업은 다음과 같습니다

[HttpPost] 
public ActionResult SomeAction(Festival model) 
{ 
    ... bla bla bla 

    // don't forget to repopulate the ViewData["Town"] value the same way you did in your GET action 
    // if you intend to redisplay the same view, otherwise the dropdown has no way of getting 
    // its values 
    ViewData["Town"] = ... same stuff as in your GET action 

    return View(model); 
} 

그리고이 모든 말했다중인, 나는 더 강하게 이상의 뷰 모델 대신이을 ViewData/ViewBag 약하게 입력 된 재료를 사용하여 당신을 추천 할 것입니다. 코드가 훨씬 깨끗해질뿐만 아니라 오류 메시지조차도 의미가 있습니다.

+0

아, 감사합니다. 감사합니다. 뷰 모델에서 쉽게 구할 수 있습니까? 나는 mvc를 이해하기 시작했습니다. – PatrickMelia

+0

나는 그것을 시도했지만 이제는 코드 뒤에 드롭 다운 목록에 오류가 있습니다. 라인 195 : 라인 195 : festival.FestivalTown.Name = fcFestival [ "Town"]; 이 문제는 무엇입니까? – PatrickMelia