如何从Controller中选择项目?

时间:2015-12-17 13:53:38

标签: asp.net-mvc model-view-controller razor

我对此非常新鲜。所以我按照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

1 个答案:

答案 0 :(得分:2)

有两种方式

解决方案1 ​​

- 保持Controller代码

@Html.DropDownListFor( i => i.AuthorID, 
     (IEnumerable<SelectListItem>) ViewData["AuthorID"]);

虽然最好将ViewData中的密钥名称从AuthorID更改为AuthorList

解决方案2

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);
}