我有一个用于图书馆的 ASP.NET Core MVC 项目,我正在尝试创建一个具有来自表单的关系的模型。
我用脚手架功能制作了这个贷款模型和控制器
public class Loan
{
[Key]
public int Id { get; set; }
[DataType(DataType.Date)]
public DateTime DueDate { get; set; }
[ForeignKey("Book")]
public int BookId { get; set; }
public virtual Book Book { get; set; }
[ForeignKey("Reader")]
public int ReaderId { get; set; }
public virtual Reader Reader { get; set; }
}
public async Task<IActionResult> Create([Bind("Id,DueDate,BookId,ReaderId")] Loan loan)
{
if (ModelState.IsValid)
{
_context.Add(loan);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["BookId"] = new SelectList(_context.Book, "Id", "Id", loan.BookId);
ViewData["ReaderId"] = new SelectList(_context.Reader, "Id", "Id", loan.ReaderId);
return View(loan);
}
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="DueDate" class="control-label"></label>
<input asp-for="DueDate" class="form-control" />
<span asp-validation-for="DueDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="BookId" class="control-label"></label>
<select asp-for="BookId" class ="form-control" asp-items="ViewBag.BookId"></select>
</div>
<div class="form-group">
<label asp-for="ReaderId" class="control-label"></label>
<select asp-for="ReaderId" class ="form-control" asp-items="ViewBag.ReaderId"></select>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
当我尝试创建新贷款时,loan.Book 和 loan.Reader 为空。 所以我尝试像这样更改 Create 方法:
public async Task<IActionResult> Create([Bind("Id,DueDate,BookId,ReaderId")] Loan loan)
{
loan.Book = _context.Book.FirstOrDefault(b => b.Id == loan.BookId);
loan.Reader = _context.Reader.FirstOrDefault(r => r.Id == loan.ReaderId);
if (ModelState.IsValid)
{
_context.Add(loan);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["BookId"] = new SelectList(_context.Book, "Id", "Id", loan.BookId);
ViewData["ReaderId"] = new SelectList(_context.Reader, "Id", "Id", loan.ReaderId);
return View(loan);
}