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?
That's normal. Value types are always required. You could make your property nullable:
public long? KategoriaWlasnaId { get; set; }
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:
[Required]
public long? KategoriaWlasnaId { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With