我对此非常新鲜。所以我按照here的教程。
到目前为止它还在运行,但我想知道如何使用现有作者创建一本新书。
My Book-Model如下:
public class Book
{
[ScaffoldColumn(false)]
public int BookID { get; set; }
[Required]
public string Title { get; set; }
public int Year { get; set; }
[Range(1, 500)]
public decimal Price { get; set; }
public string Genre { get; set; }
[ScaffoldColumn(false)]
public int AuthorID { get; set; }
// Navigation property
public virtual Author Author { get; set; }
}
AuthorID
会指向Author.AuthorID
,如此处:
public class Author
{
[ScaffoldColumn(false)]
public int AuthorID { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "First Name")]
public string FirstMidName { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
我的BooksController
内容如下:
public IActionResult Create()
{
ViewData["AuthorID"] = new SelectList(_context.Author, "AuthorID", "Author");
return View();
}
但我如何在ViewData["AuthorID"]
Create.cshtml
Form
Select
中使用此Options
?
答案 0 :(得分:2)
有两种方式
- 保持Controller代码
@Html.DropDownListFor( i => i.AuthorID,
(IEnumerable<SelectListItem>) ViewData["AuthorID"]);
虽然最好将ViewData中的密钥名称从AuthorID更改为AuthorList
public IActionResult Create()
{
ViewData["AuthorID"] = _context.Author;
return View();
}
@Html.DropDownListFor( i => i.AuthorID,
new SelectList((IEnumerable) ViewData["AuthorID"], "AuthorID", "Author"))
另外我建议创建一个新类并将其用作ViewModel,因此您可以使用该类属性,而不是在ViewData中设置数据,例如
public class BooKViewModel
{
Public IEnumerable<Author> AuthorsList {get;set;}
}
然后
public IActionResult Create()
{
var viewModel = new BookViewModel();
viewModel.AuthorsList = _context.Author;
return View(viewModel);
}