下拉列表MVC 4错误



我正在尝试创建一个下拉列表,但对我来说不起作用。该应用程序主要是一个基于节日的应用程序,您可以在其中添加节日和活动。我收到的错误是在线的:

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

这是我得到的错误:

没有具有关键字"towns"的类型为"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.cs.html

//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; }
}

我怀疑这个错误发生在您将表单提交给[HttpPost]操作时,而不是在呈现表单时,对吧?这个操作会呈现包含下拉列表的相同视图,对吗?在这个[HttpPost]操作中,您忘记了像在HttpGet操作中一样填充ViewData["Town"]值,对吧?

因此,继续使用与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弱类型的东西。不仅你的代码会变得更加干净,甚至错误消息也会变得有意义。

最新更新