<div class="form-group">
@Html.LabelFor(m => m.Genres)
@Html.DropDownListFor(m => m.Genres, new SelectList(Model.Genres, "id", "name"), "", new { @class = "form-control" })
</div>
以上是我的观点
public class GigFormViewModel
{
public string Venue { get; set; }
public string Date { get; set; }
public string Time { get; set; }
public int Genre { get; set; }
public IEnumerable<Genre> Genres { get; set; }
}
这是我的ViewModel
public class Gig
{
public int id { get; set; }
[Required]
public ApplicationUser artisrt { get; set; }
public DateTime dateTime { get; set; }
[Required]
[StringLength(255)]
public string venue { get; set; }
[Required]
public Genre genre { get; set; }
}
模型
public ActionResult Create(GigFormViewModel viewModel)
{
var artistId = User.Identity.GetUserId();
var artist = _context.Users.Single(u => u.Id == artistId);
var genre = _context.genres.Single(g => g.id == viewModel.Genre);
var gig = new Gig()
{
artisrt = artist,
dateTime = DateTime.Parse(string.Format("{0}, {1}", viewModel.Date, viewModel.Time)),
genre = genre,
venue = viewModel.Venue
};
_context.gigs.Add(gig);
_context.SaveChanges();
return RedirectToAction("Index", "Home");
}
以上是控制器,异常是从我调用genres.Single()
的位置生成的我尝试使用SingleOrDefault()而不是Single(),但在这种情况下,它尝试在数据库中保存空值,并且数据库不允许空值。
编辑:调试时,viewModel.Genre的值为0.
答案 0 :(得分:1)
你应该这样做:
@Html.DropDownListFor(m => m.Genre,
new SelectList(Model.Genres, "id", "name"), "",
new { @class = "form-control" })
其中:
m => m.Genre
是存储结果值的属性(您当前正在使用集合m =&gt; m.Genres而不是m.Genre)