Wednesday, November 21, 2012

How to Binding Dropdown Using Knockout JS


Using jquery, we access date from Action called Ko_ShowBranch in a controller caller ListObject. This action access data from database using a function called ShowAll_Branch() and to return Json result in text and value property we write below line this way.
ShowAll_Branch().Select(p => new { text =p.BranchName , value = p.ID.ToString() });

In Html Value property and Text property are set using optionsValue: and optionsText:


Javascript


 viewModel = {
        Branch: ko.observableArray()

    };

    $(function () {
        $.getJSON('http://localhost:3400/ListObject/Ko_ShowBranch', null
          function (response)  {
            viewModel.Branch(response);
        });
         ko.applyBindings(viewModel);

    });


Html

 <select data-bind="options: Branch, optionsCaption: 'Choose Branch...',
            optionsValue: function(item) { return item.value; },
            optionsText: function(item) { return item.text; }" id="Branch" name="Branch">   </select>


Controler


 public JsonResult Ko_ShowBranch()
        {
            var result = projectRepository.ShowAll_Branch().Select(p => new { text =                      p.BranchName, value = p.ID.ToString() });
            return Json(result, JsonRequestBehavior.AllowGet);
        }


No comments:

SQL Optimization

  SQL Optimization  1. Add where on your query  2. If you remove some data after the data return then remove the remove condition in the sel...