mvc dropdownlistfor 未标记为必需,但仍然是必需的
我在 cshtml 文件中有一个下拉列表:
var kategorie_wlasna = new SelectList(
(from z in Model.Kategoria
where !formReadOnly || z.Id == Model.KategoriaWlasnaId
select z),
"Id",
"Nazwa");
...
@Html.DropDownListFor(
model => model.KategoriaWlasnaId,
kategorie_wlasna,
"----",
htmlClassDropDownListDef)
在我的 viewModel 中,我的属性没有任何注释为必需:
public long KategoriaWlasnaId { get; set; }
但该字段仍然是必需的。在浏览器中我得到:
<select class="input-validation-error form_object1" data-val="true" data-val-number="The field KategoriaWlasnaId must be a number." data-val-required="The KategoriaWlasnaId field is required." id="KategoriaWlasnaId" name="KategoriaWlasnaId">
<option value="">-----</option>
<option value="1227">Wykroczenie</option>
<option value="1228">Przestępstwo</option>
</select>
我错过了什么?
I have a dropdownlistfor in cshtml file:
var kategorie_wlasna = new SelectList(
(from z in Model.Kategoria
where !formReadOnly || z.Id == Model.KategoriaWlasnaId
select z),
"Id",
"Nazwa");
...
@Html.DropDownListFor(
model => model.KategoriaWlasnaId,
kategorie_wlasna,
"----",
htmlClassDropDownListDef)
In my viewModel I have the property without any annotations as Required:
public long KategoriaWlasnaId { get; set; }
But the field is still Required. In the browser I get:
<select class="input-validation-error form_object1" data-val="true" data-val-number="The field KategoriaWlasnaId must be a number." data-val-required="The KategoriaWlasnaId field is required." id="KategoriaWlasnaId" name="KategoriaWlasnaId">
<option value="">-----</option>
<option value="1227">Wykroczenie</option>
<option value="1228">Przestępstwo</option>
</select>
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这很正常。值类型始终是必需的。您可以将属性设置为可为空:
现在不再需要该属性,并且如果用户未在下拉列表中选择任何元素,则其值将为
null
。如果您想让它成为必需的并个性化消息,您可以使用必需属性来装饰它:That's normal. Value types are always required. You could make your property nullable:
Now it will no longer be required and if the user doesn't select any element in the dropdown its value will be
null
. And if you wanted to make it required and personalize the message you could decorate it with the Required attribute:您可以通过将以下行添加到 Application_Start 方法中的
Global.asax.cs
来修改默认的DataAnnotationsModelValidatorProvider
,以便不需要值类型:You can modify the default
DataAnnotationsModelValidatorProvider
so that value types will not be required by adding the following lines toGlobal.asax.cs
in the Application_Start method:如果数据类型(使用 long)不是必须的,那么只需将 long 更改为 string
public long KategoriaWlasnaId { get; 即可。放; }
公共字符串 KategoriaWlasnaId { 获取;放; }
这也
公共长吗?类别WlasnaId { 获取;放; 另外,
如果您使用数据注释,您也可以使用 Nullable 属性
If the datatype (use long) is not a must then this will also work by just changing long to string
public long KategoriaWlasnaId { get; set; }
public string KategoriaWlasnaId { get; set; }
this also
public long? KategoriaWlasnaId { get; set; }
also if you are using data annotations you may can use Nullable attribute as well