Ahmed Alsahli Ahmed Alsahli - 5 months ago 11
AngularJS Question

Blank item always appear in select tag when binding with database table

For some reasons, I have a strange issue in my ASP.Net MVC/angularjs view. I am listing users in a hidden select tag, Once I click list to show the select tag, I see the users but there is always a blank item at the beginning of the list??! What makes it more stranger, that blank item disappear once I select any other (non blank) items.

enter image description here

enter image description here

enter image description here

View:

<select ng-options='x as (x.fName+" "+x.lName) for x in users' ng-model="uListModel"></select>


AngularJS:

$http.get('/Home/GetUsers')
.then(function (response) {
$scope.users= response.data;
})
.catch(function (e) {
console.log("error", e);
throw e;
})
.finally(function () {
console.log("This finally block");
});


MVC Controller:

public JsonResult GetSupervisor()
{
return this.Json((from userObj in db.Users
select new
{
Id = userObj.Id,
fName = userObj.usrFirstName,
lName = userObj.usrLastName,
})
, JsonRequestBehavior.AllowGet
);
}

Answer

Please try one of these two solutions:

Solution 1:

<select ng-options='x as (x.fName+" "+x.lName) for x in users' ng-model="uListModel">
       <option value="" selected="selected">Select User</option>
</select>

Solution 2:

Set initial model value:

$http.get('/Home/GetUsers')
    .then(function (response) {
        $scope.users= response.data;
        $scope.uListModel = $scope.users[0]
    })
    .catch(function (e) {
        console.log("error", e);
        throw e;
    })
    .finally(function () {
        console.log("This finally block");
    });

Or:

    <select ng-init="uListModel=users[0]" 
ng-options='x as (x.fName+" "+x.lName) for x in users' ng-model="uListModel"></select>
Comments