Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvc dropdownlistfor is not marked as required but is still required

Tags:

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?

like image 601
blackik Avatar asked Sep 05 '11 14:09

blackik


1 Answers

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; }
like image 85
Darin Dimitrov Avatar answered Sep 19 '22 18:09

Darin Dimitrov