Joël Gobeil
Joël Gobeil

Reputation: 99

How to fill a select list with AJAX?

enter image description here

I want to fill the options from a select with AJAX. What am I doing wrong?

Here's the code in my View:

 $(function() {
    $.getJSON("Animes/GetCategories", null, function(data) {
        var options = '';
        for (var x = 0; x < data.length; x++) {
            options += '<option value="' + data[x]['CategoryID'] + '">' + data[x]['CategoryNom'] + '</option>';
        }
        console.log(options);
        $('#lstCat').html(options);

    });
});

The code in my Controller :

public JsonResult GetCategories() {
    var affCat = from cats in db.Categories
    select new {
        CategoryID = cats.CategoryID,
        CategoryNom = cats.CategoryNom
    };

    return Json(affCat, JsonRequestBehavior.AllowGet);
}

The code of the select in my View:

<select id="lstCat">
    //Don't know what to place in the select
    <option>?</option>
</select><br />

Upvotes: 0

Views: 150

Answers (2)

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

As you are using Angularjs, Try to use to fully instead of mixing with jquery

try like this

Js

var app = angular.module("app", []);
app.controller("myCtrl", ["$scope", function($scope) {
    $scope.categoryList = [];
    $.getJSON("Animes/GetCategories", null, function(data) {
        $scope.categoryList = data;
    });
}]);

HTML

<div ng-app="app" ng-controller="myCtrl">
   <select id="lstCat" ng-options="category.CategoryID as category.CategoryNom for category in categoryList">
   </select>
</div>

By the way for html jquery have .html() to append html . .val() if for controls only

like this

$('#lstCat').html(options);

and from your html remove option

Like this

<select id="lstCat">
</select>

Upvotes: 3

AaronLS
AaronLS

Reputation: 38364

val is not used for adding html.

Instead of:

$('#lstCat').val(options); 

try:

$('#lstCat').html(options);

Upvotes: 0

Related Questions