模型状态中的错误消息不会显示

时间:2016-05-02 16:27:04

标签: validation html-helper

professional ASP.NET MVC 5中所述,我将制作编辑方法来编辑相册数据库中的项目。为此,我们考虑获取部分:

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

并且如书中所述,当经理为Price输入字符串(而不是数字)时,我希望显示以下消息,因此我

ModelState.AddModelError("Price", "unreasonable");

签署 POST 编辑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);
    }

最后我将@Html.ValidationMessage("Price")添加到修改查看,结果是:

<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>

然而,当我按保存按钮并将字符串作为价格时,它会向我显示默认消息: enter image description here

0 个答案:

没有答案