我試圖讓下拉列表工作,但它不適合我。此應用程序主要是一個基於節日的應用程序,您可以在活動中添加節日。我得到的錯誤是在線:下拉列表MVC 4錯誤
@Html.DropDownList("towns", (IEnumerable<SelectListItem>)ViewData["Town"], new{@class = "form-control", @style="width:250px" })
這是我的錯誤:
有型「的IEnumerable」具有關鍵的「城鎮」的無ViewData的項目。
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; }
}
啊好吧我得到你,謝謝。在視圖模型中獲取它很容易嗎?我只是開始理解mvc。 – PatrickMelia
我試過了,現在我在下面的代碼中出現了下拉列表的錯誤。第195行: 第195行:festival.FestivalTown.Name = fcFestival [「Town」]; 這是什麼問題? – PatrickMelia