我认为这将是一件容易的事,但我现在已经挣扎了一段时间。
我有Sport
属于某个对象的SportGroup
对象。
我想在组合框中表示组,并SportViewModel.cs
使用以下属性创建
public Guid Id {get; set;}
public string Name {get; set;}
public Guid? SportGroupId { get;set; }
public IEnumerable<SportGroup> SportGroups {get; set; }
HttpGet 创建动作
SportViewModel newSport = new SportViewModel();
newSport.SportGroups = new SelectList(GetAllSportGroups(), "Id", "Name");
//GetAllSportGroups() returns list of SportGroups domain objects as you can imagine.
我的创建视图看起来像这样
@model Models.SportViewModel
<div>Sport group</div>
<div>@Html.DropDownListFor(x => x.SportGroupId, Model.SportGroups)</div>
现在在控制器的httpPost
操作中,我接收数据并尝试保存它:
[HttpPost]
public ActionResult Create(SportViewModel newSport)
{
// if model state is valid and other checking omitted
// session and transaction omitted
Sport sport = new Sport();
sport.Id = newSport.Id;
sport.Name = newSport.Name;
SportGroup sportGroup = session.Load<SportGroup>(SportGroupId);
sport.SportGroups.Add(sportGroup); // here is where I'm getting an error
}
提交后我收到这些错误
你调用的对象是空的。
参考线sport.SportGroups.Add(sportGroup);
请帮忙。谢谢