Trying to create a model edit. Error pops up:

enter image description here

enter image description here enter image description here

Index.cshtml:

@{ ViewBag.Title = "Index"; Layout = "~/Views/_Layout.cshtml"; } @model justfortest.Models.Book @using (Html.BeginForm("Index", "Home", FormMethod.Post)) { <fieldset> @Html.HiddenFor(m => m.Id) <p> @Html.LabelFor(m => m.Name, "Название книги") <br /> @Html.EditorFor(m => m.Name) </p> <p> @Html.LabelFor(m => m.Author, "Автор") <br /> @Html.EditorFor(m => m.Author) </p> <p> @Html.LabelFor(m => m.Price, "Цена") <br /> @Html.EditorFor(m => m.Price) </p> <p><input type="submit" value="Отправить" /></p> </fieldset> } 

HomeController:

 BookContext db = new BookContext(); [HttpGet] public ActionResult Index() { return View(db.Books); } [HttpPost] public ActionResult Index(Book book) { db.Entry(book).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { db.Dispose(); base.Dispose(disposing); } 

There are models. DB tables are filled with data

    1 answer 1

    You submit a model with type DbSet<Book>

     return View(db.Books); 

    but you expect in the justfortest.Models.Book markup as you expect in the public ActionResult Index(Book book) method public ActionResult Index(Book book) . And you rightly get an exception, in the process of processing markup, because of mismatched types of models.

    • I changed in BookContext to public DbSet <Book> Book {get; set; } and during the transfer I changed Books to Book. The table in the database I also Book. Am I right? - Andrew_Romanuk
    • But the error is all the same - Andrew_Romanuk
    • Not. DbSet <Book> is some abstract collection of Book entities from a database. And you expect to receive one copy of Book in your marking. You need to take one element from DbSet <T> and pass it on to the view. For example, like this: db.Books.First () - Artyom Okonechnikov