Ethan
Ethan

Reputation: 163

selectedIndex is undefined in dropdownlist mvc

i am binding dropdown list but zero index showing undefined, below is my code.

  <select ng-model="CategoryID" id="CategoryID" name="CategoryID" class="form-control margin-bottom-15" required>          
        @foreach (var item in Model.Categories)
        {
            <option value="@item.Value">@item.Text</option>
        }
    </select>

after rendering its showing like...

<select ng-model="CategoryID" id="CategoryID" name="CategoryID" class="form-control margin-bottom-15 ng-pristine ng-invalid ng-invalid-required ng-touched" required="">
   <option value="? undefined:undefined ?"></option>                          
   <option value="1">Category1</option>
   <option value="2">Category2</option>
</select>

in controller..

 private IEnumerable<SelectListItem> GetCategories()
    {

        var catg = database.Categories
                    .Select(x =>
                            new SelectListItem
                            {
                                Value = x.CategoryID.ToString(),
                                Text = x.CategoryName
                            });

        return new SelectList(catg, "Value", "Text");
    }

Upvotes: 0

Views: 937

Answers (1)

Konstantin Dinev
Konstantin Dinev

Reputation: 34905

Inspect the values that your binding to because they probably look like this:

[
    { Text: "" },
    { Text: "Category1", Value: 1 }
    { Text: "Category2", Value: 2 }
]

Or you really have this value ? undefined:undefined ? as the Value property of your first item.

Upvotes: 1

Related Questions