【发布时间】:2014-02-10 15:47:57
【问题描述】:
我试图让一个下拉列表工作,但它不适合我。此应用程序主要是基于节日的应用程序,您可以在其中添加节日以及您的活动。我得到的错误在线:
@Html.DropDownList("towns", (IEnumerable<SelectListItem>)ViewData["Town"], new{@class = "form-control", @style="width:250px" })
这是我得到的错误:
没有具有键“城镇”的“IEnumerable”类型的 ViewData 项。
创建.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"];
模型.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; }
}
【问题讨论】:
标签: asp.net-mvc-4 razor html.dropdownlistfor