我发现如果我在视图模式下使用DropDownListFor,变量的[Required(ErrorMessage =“”)]将无法在表单中使用。
型号:
[Key]
[Required(ErrorMessage = "Pls input id")]
public int StaffId { get; set; }
[DisplayName("UserType")]
public int UserTypeId { get; set; }
控制器:
public ActionResult Create()
{
List<SelectListItem> listItem = new List<SelectListItem>();
listItem.Add(new SelectListItem { Text = "A", Value = "1" });
listItem.Add(new SelectListItem { Text = "B", Value = "2" });
listItem.Add(new SelectListItem { Text = "C", Value = "3" });
ViewData["List"] = new SelectList(listItem, "Value", "Text", "");
return View();
}
查看:
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.StaffId, "StaffId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.StaffId, new { htmlAttributes = new { @class = "form-control" }, })
@Html.ValidationMessageFor(model => model.StaffId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.UserTypeId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.UserTypeId, ViewData["List"] as SelectList, "請選擇", htmlAttributes: new { @class = "form-control" })
@*@Html.EditorFor(model => model.UserTypeId, new { htmlAttributes = new { @class = "form-control" } })*@
@Html.ValidationMessageFor(model => model.UserTypeId, "", new { @class = "text-danger" })
</div>
</div>
如果StaffId为null,则它将在Microsoft Visual Studio中返回错误
答案 0 :(得分:1)
如果StaffId为空.....
使用您显示的代码,视图模型的StaffId
属性(假设您使用的对象作为操作方法的参数)将永远不会为null,因为它不可为空。如果用户没有选择除默认标签以外的任何内容,则它将为0
(默认的int值)。
现在关于错误,这通常发生在您发布表单时,并且在httppost操作方法中您返回相同的视图而不重新加载填充ViewData下拉列表所需的相关集合。因此,请确保在返回视图之前重新加载集合。
[HttpPost]
public ActionResult Index(YourViewModel model)
{
if(ModelState.IsValid)
{
// to do :Save and Redirect ( PRG pattern)
}
// Let's reload the collection needed to render the dropdown
var listItem = new List<SelectListItem>(){
new SelectListItem { Text = "A", Value = "1" },
new SelectListItem { Text = "B", Value = "2" }
};
ViewData["List"] = new SelectList(listItem, "Value", "Text", "");
return View(model);
}