对于ModelState无效的项目,不显示验证消息

时间:2015-02-17 12:40:54

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

当我将设备的名称编辑为空/ 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>

CONTROLLER

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

    }

2 个答案:

答案 0 :(得分:4)

问题在于这一行:

@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 => item.Name)

答案 1 :(得分:0)

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

添加@Html.ValidationMessageFor(m => 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" })