【发布时间】:2019-11-25 09:56:18
【问题描述】:
在下一次,我可以创建一些帖子,因为我正在学习 C# 和 ASP.NET MVC。我来自 Pythonic 世界,所以有些事情对我来说不是很清楚。
我想生成一个字符串列表,然后我想在我的表单中将这个列表显示为 DropDownList。
这是我的模型:
public class Joueur
{
public int ID { get; set; }
[Required, Display(Name = "Nom"), StringLength(30)]
public string Lastname { get; set; }
[Required, Display(Name = "Prénom"), StringLength(30)]
public string Firstname { get; set; }
[Required, StringLength(15)]
public string Poste { get; set; }
public string Image { get; set; }
}
根据创建方法,这是我的控制器:
// GET: Joueurs/Create
public ActionResult Create()
{
List<Strings> posteList = new List<SelectListItem>{ "Gardien", "Défenseur", "Milieu", "Attaquant" };
ViewBag.PosteList = posteList;
return View();
}
这是我的观点:
<div class="col-md-10">
@*ViewBag.PosteList is holding all the postes values*@
@Html.DropDownListFor(model => model.Poste, ViewBag.PosteList as SelectList, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Poste, "", new { @class = "text-danger" })
</div>
但我遇到了这个问题:
@Html.DropDownListFor(model => model.Poste, ViewBag.PosteList as SelectList, new { @class= "form-control" })
没有类型为“IEnumerable”且键为“Poste”的 ViewData 元素。
我该怎么做?
使用 Django 非常简单,在我的模型中我创建了一个字典并在属性中传递了这个字典,但是使用 C# ASP.NET?我没有办法做到这一点。
【问题讨论】:
-
您没有将
Joueur类作为模型发送到看起来的视图。有关示例,请参阅 https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/accessing-your-models-data-from-a-controller。
标签: c# asp.net asp.net-mvc