mvc dropdownlistfor is not marked as required but is still required
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; }
You can modify the default DataAnnotationsModelValidatorProvider so that value types will not be required by adding the following lines to Global.asax.cs in the Application_Start method:
ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(new DataAnnotationsModelMetadataValidatorProvider());
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
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
加载中,请稍侯......
精彩评论