I wanted to create a model edit using template helpers. I did everything as the author in this book: https://metanit.com/sharp/mvc5/5.4.php

But, it gives an error that the resource was not found. What is the problem ?

enter image description here

Controller:

public class HomeController : Controller { BookContext db = new BookContext(); // GET: Home public ActionResult Index(int? id) { if (id == null) { return HttpNotFound(); } Book book = db.Books.Find(id); if (book != null) { return View(book); } return HttpNotFound(); ; } [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); } } 

Index.cshtml:

 **@{ ViewBag.Title = "Index"; Layout = "~/Views/_Layout.cshtml"; } @model justfortest.Models.Book <h2> Книга β„– @Model.Id </h2> @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> }** 

BookContext:

 public class BookContext: DbContext { public BookContext() : base("BookContext") { } public DbSet<Book> Books { get; set; } public DbSet<Purchase> Purchases { get; set; } } 

Model Book:

  public class Book { // ID ΠΊΠ½ΠΈΠ³ΠΈ public int Id { get; set; } // Π½Π°Π·Π²Π°Π½ΠΈΠ΅ ΠΊΠ½ΠΈΠ³ΠΈ public string Name { get; set; } // Π°Π²Ρ‚ΠΎΡ€ ΠΊΠ½ΠΈΠ³ΠΈ public string Author { get; set; } // Ρ†Π΅Π½Π° public int Price { get; set; } } 

justfortest- project name

BookStore - the name of the database

There is an entry in the database.

    1 answer 1

    Everything works as it should. You return a 404 error in your controller if the book is not found or id == null .

     return HttpNotFound(); 

    So when you call the URL / Home / Index, the id parameter is null , naturally the controller generates an error 404