【问题标题】:Properly creating a dropdownlistfor in ASP.NET MVC在 ASP.NET MVC 中正确创建下拉列表
【发布时间】: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


【解决方案1】:

如果你得到 null 那么你应该发送空字符串。或许能解决你的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    • 2013-12-20
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多