【问题标题】:Validation message is not shown for an item with ModelState invalid没有为 ModelState 无效的项目显示验证消息
【发布时间】:2015-02-17 12:40:54
【问题描述】:

当我将设备的名称编辑为空/null 以致 ModelState 无效时,如何返回所有设备的列表,但显示一个已编辑的设备并显示必须输入名称的验证消息?

目前验证错误仅在设备表上可见,但我想在 TextBoxFor Helper 的左侧显示验证消息。

为什么那里看不到验证消息?

查看

@model IEnumerable<MVCTest.Models.DeviceViewModel>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>

@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<table class="table">
    <tr>
        <th>

        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        using (Html.BeginForm("Save", "Device"))
        {
            <tr>
                <td style="background: alice;">
                    @Html.ValidationMessageFor(m => item.Name)
                </td>
                <td>
                    @Html.TextBoxFor(modelItem => item.Name)
                </td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                    @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                    @Html.ActionLink("Delete", "Delete", new { id = item.Id })
                </td>
                <td>
                    <input type="submit" value="Save" />
                </td>
            </tr>
        }
    }
</table>

控制器

public class DeviceController : Controller
    {
        private List<DeviceViewModel> GetDevices()
        {
            return new List<DeviceViewModel>
            {
                new DeviceViewModel{ Id = 1, Name = "Test 1"},
                new DeviceViewModel{ Id = 1, Name = "Test 2"},
                new DeviceViewModel{ Id = 1, Name = "Test 3"},
            };
        }

        // GET: Device
        public ActionResult Index()
        {
            var devices = GetDevices();
            return View(devices);
        }

        public ActionResult Save(DeviceViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                // save to db
                return RedirectToAction("Index");
            }

            return View("Index", GetDevices());
        }
    }

视图模型

  public class DeviceViewModel
    {
        public int Id { get; set; }

        [Required(ErrorMessage = "You must enter a name!")]
        public string Name { get; set; }

    }

【问题讨论】:

    标签: c# asp.net asp.net-mvc razor asp.net-mvc-5


    【解决方案1】:

    问题出在这一行:

    @Html.ValidationMessageFor(m => item.Name,"")
    

    它使用空白错误消息作为specified message

    改成:

    @Html.ValidationMessageFor(m => item.Name)
    

    或者:

    @Html.ValidationMessageFor(m => item.Name,"A custom error message.")
    

    更新

    您还需要将您的 viewModel 返回到该视图,而不是在发布后创建一个新的。

    public ActionResult Save(DeviceViewModel viewModel)
    {
        if (ModelState.IsValid)
        {
            // save to db
            return RedirectToAction("Index");
        }
    
        return View("Index", viewModel);
    }
    

    为了将您的收藏发送回服务器,您需要使用for 循环而不是foreach

    请看这里:http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

    @foreach (var i = 0; i< Model.Count(); i++)
        {
            using (Html.BeginForm("Save", "Device"))
            {
                <tr>
                    <td style="background: alice;">
                        @Html.ValidationMessageFor(m => Model[i].Name)
                        @Html.HiddenFor(m => m.Id)
                    </td>
                    <td>
                        @Html.TextBoxFor(modelItem =>  Model[i].Name)
                    </td>
                    <td>
                        @Html.ActionLink("Edit", "Edit", new { id =  Model[i].Id }) |
                        @Html.ActionLink("Details", "Details", new { id =  Model[i].Id }) |
                        @Html.ActionLink("Delete", "Delete", new { id =  Model[i].Id })
                    </td>
                    <td>
                        <input type="submit" value="Save" />
                    </td>
                </tr>
            }
        }
    

    我确实认为您需要在保存数据时将集合发布回服务器,并且在您现有的代码中有一个可编辑的文本框@Html.TextBoxFor(modelItem =&gt; item.Name)

    【讨论】:

    • 我认为它正在从我的 DeviceViewModel 中获取 ErrorMessage 字符串?
    • 当我使用你的:@Html.ValidationMessageFor(m => item.Name, "A custom error message.") 然后总是呈现“自定义错误消息”文本???
    • @Pascal 是的,您只需替换它。这只是一个例子。
    • @Pascal 我会使用我建议的第一个,即@Html.ValidationMessageFor(m =&gt; item.Name)
    【解决方案2】:

    请确保您在布局中添加了@Scripts.Render("~/bundles/jqueryval")

    添加@Html.ValidationMessageFor(m =&gt; item.Name)并确保您已添加

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    编辑

    你必须添加ModelState.AddModelError("key", "message");

    尝试改变,看看会发生什么

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    

    @Html.ValidationSummary(false, "", new { @class = "text-danger" })
    

    【讨论】:

    • 我做了你所有的建议,但名称的错误根本不可见。我用最新的代码更新了我的问题。
    猜你喜欢
    • 2021-08-08
    • 2014-01-04
    • 2023-03-08
    • 2021-09-10
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多