You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC 4中使用ViewModel时如何实现Html.ValidationMessage?

解决ASP.NET MVC 4中ViewModel与Html.ValidationMessage的验证显示问题

你遇到的核心问题是验证错误没有和ViewModel的属性正确关联,再加上View里的表单控件没有使用强类型绑定,导致验证消息无法正常显示。下面一步步帮你搞定:


1. 优化ViewModel:用DataAnnotations实现自动验证(推荐)

这是MVC官方推荐的验证方式,比手动判断null更优雅,还能支持客户端验证。修改你的CostVM类,给需要验证的属性添加特性:

using System.ComponentModel.DataAnnotations;

public class CostVM
{
    // 给nama属性添加必填验证,指定错误提示
    [Required(ErrorMessage = "This Field Can't Empty")]
    public string nama { get; set; }

    // 其他属性保持不变
    public string alamat { get; set; }
    public string jk { get; set; }
    public string kelas { get; set; }
    public string jenis { get; set; }
}

2. 简化Controller的Post方法

MVC会自动根据ViewModel的验证特性检查ModelState有效性,不需要手动判断model.nama是否为null:

[HttpPost]
public ActionResult SetDataInDataBase(CostVM model)
{
    // 验证不通过时,重新加载下拉列表(Post后ViewBag会丢失)
    if (!ModelState.IsValid)
    {
        ViewData["jenisList"] = new SelectList(db.isengs, "jenis", "jenis");
        return View(model);
    }

    // 验证通过,保存数据到数据库
    informasi item = new informasi();
    item.nama = model.nama;
    item.alamat = model.alamat;
    item.jk = model.jk;
    item.kelas = model.kelas;
    item.jenis = model.jenis;

    db.informasis.Add(item);
    db.SaveChanges();

    return RedirectToAction("Edit", "Register", new { id = item.id, id2 = item2.Id });
}

3. 修改Razor View:使用强类型绑定

原来的View用的是普通HTML控件,没有和ViewModel绑定,需要改成MVC的强类型辅助方法,让验证消息和属性关联:

@model CostVM <!-- 必须声明强类型模型 -->

<!-- 显示nama属性的验证消息 -->
@Html.ValidationMessageFor(m => m.nama, "", new { @class = "text-danger" })

<div class="container">
    <div class="form-group">
        <label>Nama:</label>
        @Html.TextAreaFor(m => m.nama, new { @class = "form-control" })
    </div>
    <div class="form-group">
        <label>Alamat:</label>
        @Html.TextBoxFor(m => m.alamat, new { @class = "form-control", placeholder = "Enter Alamat", required = "required" })
    </div>
    <div class="form-group">
        <label>JK:</label>
        @Html.RadioButtonFor(m => m.jk, "L", new { required = "required" }) L<br />
        @Html.RadioButtonFor(m => m.jk, "P") P<br />
    </div>
    <div class="form-group">
        <label>Kelas:</label>
        @Html.DropDownListFor(m => m.kelas, new List<SelectListItem>
        {
            new SelectListItem { Text = "--Pilih Kelas--", Value = "" },
            new SelectListItem { Text = "1", Value = "1" },
            new SelectListItem { Text = "2", Value = "2" },
            new SelectListItem { Text = "3", Value = "3" }
        }, new { @class = "form-control", required = "required" })
    </div>
    <div class="form-group">
        <label>Jenis:</label>
        @Html.DropDownListFor(m => m.jenis, ViewBag.jenisList as SelectList, "--Jenis--", new { @class = "form-control", required = "required" })
    </div>
    <div class="button">
        <button type="submit">Submit</button> <!-- 必须加type="submit"触发表单提交 -->
    </div>
</div>

<!-- 引入jQuery验证脚本,实现客户端实时验证(可选但体验更好) -->
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

如果你坚持手动添加ModelError(不推荐)

如果不想用DataAnnotations,那需要把ModelState.AddModelError的键改成ViewModel属性的名称,让验证消息和属性关联:

if (string.IsNullOrEmpty(model.nama))
{
    // 用属性名作为错误键,和View里的ValidationMessageFor对应
    ModelState.AddModelError(nameof(CostVM.nama), "This Field Can't Empty");
    ViewData["jenisList"] = new SelectList(db.isengs, "jenis", "jenis");
    return View(model);
}

然后View里依然用@Html.ValidationMessageFor(m => m.nama)就能显示错误了。


内容的提问来源于stack exchange,提问作者Ihsan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:16:45