Koteczeg
Koteczeg

Reputation: 167

How to set null value (by default) to drop-down list in MVC 4

In my model class for view, I have an enum type property SubjectType:

[Required(ErrorMessage = "This field is required.")]
public SubjectType SubjectType { get; set; }

I would like to create drop-down list for this property. But by default I would like it to be set to null so that user has to choose something, and the validation message will be shown if he would try to submit form without choosing any option.

What is the best approach to achieve this?

I was trying to change SubjectType property to nullable, and setting the default value to null, but the validation still passed on this field (somehow) and the form was submitted to the server. By default the value of this field was set to the first value from enum definition. No JavaScript allowed, I'd like to keep everything in code-behind. I will be grateful for any advice.

so far i render it this way:

@Html.DropDownList("SubjectType", EnumHelper.GetSelectList(typeof(SubjectType)))
@Html.LabelFor(model => model.SubjectType)
@Html.ValidationMessageFor(model => model.SubjectType)

Upvotes: 1

Views: 2260

Answers (2)

Charles McIntosh
Charles McIntosh

Reputation: 661

Edit: I think the problem was three fold. first your attribute is named SubjectType but your dropdown is named Type so it cannot be bound to SubjectType.

second, Apparently you have to use @HTML.dropdownlistfor(). I did a viewsource with my two different versions dropdown and dropdownlistfor and dropdownlistfor is the only one that adds the validation classes (see below)

third, we needed to add the option label parameter "Select a Type" as a default value. I'm sure it'll work for you now.

In Model:

[Required(ErrorMessage = "Error!")]
public string SubjectType{ get; set; }

In Html:

@Html.DropDownListFor(m => m.SubjectType, new SelectList(Enum.GetNames(typeof(SubjectType))), "Select a Type", new { @class = "pretty" } )

now I see you have a helper that furnishes an enumerable I think that will be just fine if you replace my second param with that.

Dropdownlist vs DropdownlistFor Rendering of Select Element:

DropdownList:

<select name="SubjectType" class="pretty" id="SubjectType">...</select>

DropdownListFor:

<select name="SubjectType" class="pretty" id="SubjectType" data-val-required="Error!" data-val="true">...</select>

As you can see data-val-required and data-val classes are missing when doing a simple dropdown thus not turning on validation FOR that attribute. Sorry for all the pain of getting here. Don't forget to mark me right if it works.

Upvotes: 0

Marek Sob.
Marek Sob.

Reputation: 26

You are able to solve problem doing this: Change submit button to button with onclick action, then validate it in javascript and if form and this enum field is valid submit the form using jQuery.

Upvotes: 1

Related Questions