【发布时间】: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