MVC 5 DropdownlistFor不验证
问题描述:
我有一个dropdownlistfor和一个验证字段,但没有验证正在发生。 验证字段的所有其他字段正在验证。任何人有一个想法?MVC 5 DropdownlistFor不验证
我的视图模型:
[Display(Name = "Organisation")]
[Required(ErrorMessage = "Organisation is required.")]
public Guid OrganisationId{ get; set; }
public SelectList Organisations { get; set; }
我的控制器:
public ActionResult Create()
{
IEnumerable<Organisation> organisations = _organisationService.FindAll();
var model = new RegisterViewModel
{
Organisations = new SelectList(organisations, "Id","Name")
};
return View(model);
}
笔者认为:
<div class="form-group row">
@Html.DropDownListFor(model => model.OrganisationId, Model.Organisations, "Select a value...", new { @class = "form-control choice" })
@Html.ValidationMessageFor(model => model.OrganisationId)
</div>
答
最有可能的原因是因为你使用Guid?
说。您使用的参数类型为Nullable
,因此它可以接受空值。这就是为什么它没有验证。
尝试将Guid?
更改为Guid
。
我有Guid。我试图让它可以为空,但那没有奏效。 – Talsja
对不起,我的Viewmodel是Guid OrganisationId而不是Guid? – Talsja
是的,试试.. – ykh