我有这两个类: State和Station:
public class State
{
public int Id { get; set; }
[Required]
public string Code { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<Station> Stations { get; set; }
}
和
public class Station
{
public int Id { get; set; }
[Required]
public string Code { get; set; }
[Required]
public string Name { get; set; }
[Required]
public virtual State State { get; set; }
}
设计是“代码优先”,我使用迁移来设置数据库,它就像:
车站表将 StateId 保存为外键,因为它应该
我的StationsController.cs文件有一个Create方法,我用它ViewBag来列出这样的状态名称:
// GET: Stations/Create
public IActionResult Create()
{
ViewBag.StatesList = _context.States.ToList();
return View();
}
最后我的HttpPost Create方法
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Code,Name,State")] Station station)
{
if (ModelState.IsValid)
{
_context.Add(station);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(station);
}
我的create.cshtml文件有这样的<select>标签:
<div class="form-group">
<label asp-for="State" class="control-label"></label>
<select asp-for="State" asp-items="@(new SelectList(ViewBag.StatesList, "Id", "Name","State"))" ></select>
<span asp-validation-for="State" class="text-danger"></span>
</div>
我面临的问题是,单击 后submit,我的ModelState.isValid遗体false和State字段null如下图所示:
状态字段为空
在Controller已经自动生成的,只有两件事情我已经改变了:第一个是,我已经添加了ViewBag.StateList在Create()方法和第二个是我加了State现场Create([Bind("Id,Code,Name,State")]。
相关分类