0

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: enter image description here

Masood Moghini
  • 374
  • 3
  • 13
  • Because the `DefaultModelBinder` has already added the default error message before you have manuallr added yours (and only the first error message is displayed) –  May 05 '16 at 22:57
  • so what I have to do to substitute the default error message with the mine? – Masood Moghini May 11 '16 at 05:08
  • Why would you want to change it so something that is meaningless to a user? But refer [this answer](http://stackoverflow.com/questions/6214066/how-to-change-default-validation-error-message-in-asp-net-mvc) –  May 11 '16 at 05:11

0 Answers0