Reputation: 315
I'm using JavaScript to get the selected value of a drop list in MVC 4 but have an issue I think is caused by the HTMLHelper.
CONTROLLER - to populate droplist
private string PopulateStandard(object selectedValue = null)
{
var query = db.Database
.SqlQuery<StandardModel>(
"SELECT * FROM [DBO].[GetStandards] ('" +
User.Identity.Name + "', '" + DateTime.UtcNow + "')")
.ToList();
ViewBag.Standard = new SelectList(query, "Standard", "Standard", selectedValue);
try { return query[0].Standard; }
catch { return ""; }
}
VIEW
The view has this section for the drop list. Please note the inclusion of "All". I think this is the problem. That puts a first row atop the drop list saying "All" with a null value. I want that. So far so good (so what)
@Html.DisplayNameFor(m => m.Standard)
@Html.DropDownList("Standard", "All")
JAVASCRIPT
It's a long story, but I have other code that requires me to get the value of the drop list using JavaScript, so I'm doing it like this:
var e = document.getElementById("Standard");
var sStandard = e.options[e.selectedIndex].value;
PROBLEM
If no value was chosen, then I should get the first row, which would be "All" for text or "" for value. Instead, I'm getting the second row, which is the first one with data as populated from the database.
Is the HTML helper causing me to not get the first row? Or is my JavaScript off?
EDIT - to show ViewSource on drop list
These are the first few lines of the rendered list
<select id="Standard" name="Standard"><option value="">All</option>
<option value="2S">2S</option>
<option value="Aero">Aero</option>
Upvotes: 2
Views: 155
Reputation: 1380
@Html.DropDownList("Standard", "All")
here "All" is option label. so you do not get this as value.
Upvotes: 1