【发布时间】:2016-05-15 16:58:14
【问题描述】:
我正在尝试使用 Razor 在 ASP.NET MVC 中创建一个简单的 DropDownListFor,但我似乎无法正确理解它是如何工作的。我正在使用实体框架从数据库中提取数据,在我的 Controller 方法中它看起来像这样:
using (var entity = new DatabaseEntities())
{
ViewBag.CityList = entity.city.ToList();
return View();
}
我正在向另一个表添加值,我的视图如下所示:
<div class="form-group">
@Html.DropDownListFor(x => x.id_city, new SelectList(@ViewBag.CityList,"id_city","city1"),"Wybierz miasto", new { @class = "form-control" })
</div>
我的模型看起来像:
城市模型
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public int id_city { get; set; }
[Required(ErrorMessage = "Podaj prawidlowy kod pocztowy")]
public string postcode { get; set; }
[Required(ErrorMessage = "Podaj prawidlowa nazwe miejscowosci")]
public string city1 { get; set; }
public virtual ICollection<student> student { get; set; }
etc.
学生模型(只有重要数据,不起作用)
[ForeignKey("city")]
public int id_city { get; set; }
public virtual city city { get; set; }
现在我抛出了 ArgumentNullException,它告诉我
值不能为空。参数名称:System.Web.Mvc中的项目
我只想将 City 数据库中现有行的值添加到 Student 模型。我做错了什么?
【问题讨论】:
-
请检查一下,您是从 city 表中获取任何数据还是为空?
-
@shahim reza,空
-
该视图中的模型是什么?您是否要为学生选择城市?)您需要显示相关信息。
标签: c# asp.net asp.net-mvc razor asp.net-mvc-5