as mentioned in professional ASP.NET MVC 5 I'm going to craft an Edit method for editing an item in Albums database.to do so we consider the get part:
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Album album = db.Albums.Find(id);
if (album == null)
{
return HttpNotFound();
}
ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);
ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);
return View(album);
and as described In the book I want the following message be displayed when the manager entered a string(instead of number) for Price so I
ModelState.AddModelError("Price", "unreasonable");
after the signature of the POST Edit function.resulting:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="AlbumId,GenreId,ArtistId,Title,Price,AlbumArtUrl")] Album album)
{
ModelState.AddModelError("Price", "unreasonable");
if (ModelState.IsValid)
{
db.Entry(album).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);
ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);
return View(album);
}
and finally I add @Html.ValidationMessage("Price")
to Edit View which results in :
<div class="form-group">
@Html.LabelFor(model => model.Price, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Price)
@Html.ValidationMessage("Price")
</div>
</div>
however when I press Save button with a string as Price it gives me the default message: