Reputation: 99
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
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
Reputation: 38364
val
is not used for adding html.
Instead of:
$('#lstCat').val(options);
try:
$('#lstCat').html(options);
Upvotes: 0