-1

I want null option selected displayed as --Select-- by default in my dropDown. I'm trying to do it like this

<select class="form-control" asp-for="EducationId" asp-items="@(new SelectList(Model.educations, "Id", "Name"))"><option>--Select--</option></select>

It loads dropdown perfectly with --Select-- option selected but it does not make its value null. And when I try to get it value without selecting any option doing this

$('#EducationId option:selected').text()

It returns string having --Select--

But I want it to return null

I've tried this solution by adding disabled selected but according to its statement, once I select any option, it does not allow me to select that first option again. but in my case, this dropdown is optional and user can un-select any selected option.

How could I make this dropdown optional?

Any kind of help will be appreciated.

Community
  • 1
  • 1
Naila Akbar
  • 3,033
  • 4
  • 34
  • 76
  • 1
    why not use $('#EducationId option:selected').val() – Usman Apr 15 '17 at 19:55
  • 1
    $('#EducationId option:selected').text() will return the text in the option tag. As @Usman pointed out, use $('#EducationId option:selected').val() to get the actual value of that option tag. – gaganshera Apr 15 '17 at 19:57
  • I've tried `val()` but it also returns --Select-- – Naila Akbar Apr 15 '17 at 20:05
  • `` and then `var selected = $('#EducationId'),val();` would return `null` if the first option is selected. –  Apr 17 '17 at 09:31
  • no, it returns empty string. @StephenMuecke – Naila Akbar Apr 27 '17 at 11:24
  • No it does not. –  Apr 27 '17 at 11:26
  • I don't know..but I checked its type `typeof($('#EducationId').val())` and it returns string... – Naila Akbar Apr 27 '17 at 11:31
  • It posts back as `null` (and if property `EducationId` is nullable, then it will be bound to `null` and its its not nullable, a `ModelSate` error will be generated. –  Apr 27 '17 at 11:46
  • I'm not handling it on a post back request.. I'm validating it in javascript.. there I always find it as string.. even the solution I'm doing right now is also return -1 as string... – Naila Akbar Apr 27 '17 at 11:53

1 Answers1

2

The educations is a bunch of items you are presenting to the user to select from. Simply add another item to it like this (I am assuming it is called Education):

Model.educations.Insert(0, new Education{Id = -1, Name = "--Select--" });

Then check if that item has been selected and do whatever you need to do.

CodingYoshi
  • 25,467
  • 4
  • 62
  • 64
  • getting idea from your answer, I handled my issue with minor change.. `asp-items="@(new SelectList(Model.educations, "Id", "Name"))">` and to check for null/ not selected value `if ($('#EducationId').val() == '-1') ` – Naila Akbar Apr 27 '17 at 11:36
  • I got idea from you.. so here I'm marking it as answer. Thank you :) – Naila Akbar Apr 27 '17 at 11:38