2

In my controller:

 public ActionResult GetCountryList() {
     return Json(new {data = db.Country.ToList()},JsonRequestBehavior.AllowGet);
 }

in my ko:

self.GetCountryList = function () {
    $.getJSON("/ProfileCore/GetCountryList", function (result) {
        self.LocationList(result.data);
        console.log(self.LocationList());
    })
};

select html:

<select data-placeholder="Location" class="chosen-select" style="width:100%;" tabindex="2" data-bind="options:LocationList, optionsText:'CountryName', optionsValue:'Id', value:Location"></select>

when I view the console log this is the result: console result

the result is there is no data in select option. any suggest in how to do this in the right way? thanks

4
  • What do you mean on "no data in select option"? There is no items in it if you open the dropdown? Or your current Location is not preselected? Commented Jan 14, 2014 at 12:51
  • no items in dropdown. your right that's what I meant Commented Jan 14, 2014 at 12:51
  • I don't see anything wrong with your code. self.LocationList is an observableArray, I assume. Not a plain observable. Can you perhaps make a little fiddle with mocked data? It will be easier to debug. Commented Jan 14, 2014 at 12:52
  • yes it's an observablearray. ok I will create a fiddle for it Commented Jan 14, 2014 at 12:57

1 Answer 1

1

This is how I would do it:

// Create an object 
var Country = function (Id, Name) {
        self = this;
        self.Id = Id;
        self.CountryName = Name;
    }

// Create a mapping object
    var mapping = {
        'LocationList': {
            create: function(options) {
                return new Country(options.data.Id, options.data.CountryName);
            }
        }
    }

// Create the view model
function AViewModel()
{
  var self = this;  
    self.LocationList = ko.observableArray();
    self.Location = ko.observable("2");

    // Map the json to the view model
    $.ajax({
       url:"/echo/json/",
       data:data,
       type:"POST",
       success:function(response)
       {
         self.LocationList = ko.mapping.fromJS(response, mapping, self);
       }
    });


}

var viewModel = new AViewModel();
ko.applyBindings(viewModel);

jsFiddle with mock json call:

http://jsfiddle.net/hutchonoid/Tnyqp/10/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.