issue while submitting cascading dropdown using knockout

I have created a cascading dropdown using knockoutjs i.e. i retrieved data from database and bind to dropdown using knockout.now i stuck while submitting data to database, how to submit data using knockout to database:

         <script src="~/Scripts/jquery-1.8.2.min.js"></script>
          <script src="~/Scripts/knockout-2.2.0.js"></script>
          <script type="text/javascript">
       $(document).ready(function () {
        FetchCountries();
        $("#Country").change(function () {
            var countryId = $("#Country").val();
            $.ajax({
                type: "GET",
                url: "http://localhost:62830/api/Location/GetStates/" + countryId,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response != "") {
                        $(response).each(function (index, element) {
                            viewModel.stateCollection.push(element);
                        });
                        ko.applyBindings(viewModel);
                    }
                }
            });
        });

          $("#State").change(function () {
            var stateId = $("#State").val();
            $.ajax({
                type: "GET",
                url: "http://localhost:62830/api/Location/GetCities/" + stateId,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response != "") {
                        $(response).each(function (index, element) {
                            viewModel.cityCollection.push(element);
                        });
                        ko.applyBindings(viewModel);
                    }
                }
            });
          });


          function FetchCountries() {
            viewModel = {
                countryCollection: ko.observableArray(),
                stateCollection: ko.observableArray(),
                cityCollection: ko.observableArray()
            };
            $.ajax({
                type: "GET",
                url: "http://localhost:62830/api/Location",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response != "") {
                        $(response).each(function (index, element) {
                            viewModel.countryCollection.push(element);
                        });
                        ko.applyBindings(viewModel);
                    }
                }
            });
        }


        var sel = document.getElementById('Country'),
            myVar = sel.options[sel.selectedIndex].value;
        var sel = document.getElementById('State'),
            myVar1 = sel.options[sel.selectedIndex].value;
        var sel = document.getElementById('City'),
            myVar2 = sel.options[sel.selectedIndex].value;
        alert(myVar2)

        function viewmodel() {
            var Employee = {};
            Employee.FirstName = ko.observable(),
            Employee.LastName = ko.observable(),
            Employee.countryCollection = myVar,
            Employee.stateCollection = myVar1,
            Employee.cityCollection = myVar2
        }

        $('#btnSubmit').live("click", function (e) {
            $.ajax({
                url: '/Home/Submit/',
                async: true,
                cache: false,
                type: 'post',
                data: ko.toJSON(viewmodel),
                contentType: 'application/json',
                success: function (result) {

                }
            });
         });
       });
      </script>

      <h2>Cascading DropDown using Knockout</h2>
       FirstName:
       <input type="text" id="txtFirstName" 
              name="txtFirstName" data-bind="value:FirstName" />
       <br />
        LastName:
           <input type="text" id="txtLastName" 
              name="txtFirstName" data-bind="value:LastName" />
       <br />
       Country Name:
        <select data-bind="options: countryCollection, optionsCaption: 'Choose country...',
         optionsValue: function (item) { return item.CountryId; },
         optionsText: function (item) { return item.CountryName; }, value: Country,
          valueUpdate: 'change'"
          id="Country" name="Country">
         </select>
        <br />

State Name:
<select data-bind="options: stateCollection, optionsCaption: 'Choose state...',
    optionsValue: function (item) { return item.StateId; },
    optionsText: function (item) { return item.StateName; },  value: State,
    valueUpdate: 'change'"
    id="State" name="State">
</select>
<br />

City Name:`enter code here`
<select data-bind="options: cityCollection, optionsCaption: 'Choose city...',
    optionsValue: function (item) { return item.CityId; },
    optionsText: function (item) { return item.CityName; }, value: City,
    valueUpdate: 'change'"
    id="City" name="City">
</select>

<input type="submit" value="Submit" id="btnSubmit" />



   **controller class:**

   [HttpPost]
    public ActionResult Submit(object bind)
    {
        string fname = Request.Form["txtfirstName"];
        string lname = Request.Form["txtlastName"];
        return View();
    }



    model class:


 public class CityDTO
{
    public int StateId { get; set; }
    public int CityId { get; set; }
    public string CityName { get; set; } 
}


public class CountryDTO
{
    public int CountryId { get; set; }
    public string CountryName { get; set; }        
}


public class StateDTO
{
    public int StateId { get; set; }
    public int CountryId { get; set; }
    public string StateName { get; set; }   
}

 public static class Converter
{
    //public static Countries CountryDTOTOCountries(CountryDTO d)
    //{
    //    return new Countries
    //    {
    //        CountryId = d.CountryId,
    //        CountryName = d.CountryName
    //    };
    //}

    public static CountryDTO CountriesToCountryDTO(tblCountry e)
    {
        return new CountryDTO
        {
            CountryId = e.CountryID,
            CountryName = e.CountryName
        };
    }

    public static List<CountryDTO> LCountriesToCountryDTO(List<tblCountry> e)        
    {
        List<CountryDTO> lstCountryDTO = e.Select(
          country => new CountryDTO()
          {
              CountryId = country.CountryID,
              CountryName = country.CountryName
          }).ToList();
        return lstCountryDTO; 
    }

    public static StateDTO StatesToStateDTO(tblState e)
    {
        return new StateDTO
        {
            StateId = e.StateID,
            StateName = e.StateName
        };
    }       

    public static List<StateDTO> LStatesToStateDTO(List<tblState> e)
    {
        List<StateDTO> lstStateDTO = e.Select(
         state => new StateDTO()
         {
             StateId = state.StateID,
             StateName = state.StateName
         }).ToList();
        return lstStateDTO;
    }

    public static CityDTO CitiesToCityDTO(tblCity e)
    {
        return new CityDTO
        {
            CityId = e.CityID,
            CityName = e.CityName
        };
    }

    public static List<CityDTO> LCitiesToCityDTO(List<tblCity> e)
    {
        List<CityDTO> lstCityDTO = e.Select(
         city => new CityDTO()
         {
             CityId = city.CityID,
             CityName = city.CityName
         }).ToList();
        return lstCityDTO;
    }
   }




    public class LocationRepository : ILocationRepository
   {
    public List<CountryDTO> GetCountries()
    {
        using (sampleEntities1 dbcontext1 = new sampleEntities1())
        {
            var lstCountries = from r in dbcontext1.tblCountries select r;
            List<CountryDTO> lst = new List<CountryDTO>();
            lst = Converter.LCountriesToCountryDTO(lstCountries.ToList());
            return lst;
        }
    }

    public List<StateDTO> GetStates(int countryId)
    {
        using (sampleEntities1 dbcontext = new sampleEntities1())
        {
            //var lstStates = from r in dbcontext.States select r;                 
     //dbcontext.States.Where(x => x.CountryId == countryId).Select(x => new {
      x.StateId, x.StateName }).ToList();                
            var lstStates = dbcontext.tblStates.Where(b => b.CountryID ==    

          countryId).ToList();
            List<StateDTO> list = new List<StateDTO>();
            list = Converter.LStatesToStateDTO(lstStates.ToList());
            return list;
        }
    }

    public List<CityDTO> GetCities(int stateId)
    {
        using (sampleEntities1 dbcontext = new sampleEntities1())
        {
            //var lstStates = from r in dbcontext.States select r;  
       //dbcontext.States.Where(x => x.CountryId == countryId).Select(x => new { 
      x.StateId, x.StateName }).ToList();                
            var lstCities = dbcontext.tblCities.Where(b => b.StateID == 
       stateId).ToList();
            List<CityDTO> list = new List<CityDTO>();
            list = Converter.LCitiesToCityDTO(lstCities.ToList());
            return list;
        }
    }
    }

Answers


When you are working with knockout try to use ko as much as you can. for instance, instead of using jquery on change you can subscribe to country observable.secondly you should use click binding over jquery on click. there is no need of multiple applyBindings also.

So your view model will be like this :-

function viewmodel() {
 var self = this;

self.Employee = {};
self.Employee.FirstName = ko.observable();
self.Employee.LastName = ko.observable();
self.Employee.country = ko.observable();;
self.Employee.state = ko.observable();;
self.Employee.city = ko.observable();;

//Countries
self.fn = function () {};
self.fn.countryCollection: ko.observableArray();
self.fn.stateCollection: ko.observableArray();
self.fn.cityCollection: ko.observableArray();

self.submit = function () {
    $('#btnSubmit').live("click", function (e) {
        $.ajax({
            url: '/Home/Submit/',
            async: true,
            cache: false,
            type: 'post',
            data: ko.toJS(self),
            contentType: 'application/json',
            success: function (result) {

            }
        });
    });
 }
 //subscribe to get seleted country value
 self.Employee.country.subscribe(function (newValue) {
    var countryId = newValue;
    $.ajax({
        type: "GET",
        url: "http://localhost:62830/api/Location/GetStates/" + countryId,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            if (response != "") {
                $(response).each(function (index, element) {
                    self.fn.stateCollection.push(element);
                });
            }
        }
    });
 });
 //subscribe to get seleted country value
 self.Employee.state.subscribe(function (newValue) {
    var stateId = newValue;
    $.ajax({
        type: "GET",
        url: "http://localhost:62830/api/Location/GetCities/" + stateId,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            if (response != "") {
                $(response).each(function (index, element) {
                    self.fn.cityCollection.push(element);
                });
            }
        }
    });
});

function FetchCountries() {
    $.ajax({
        type: "GET",
        url: "http://localhost:62830/api/Location",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            if (response != "") {
                $(response).each(function (index, element) {
                    self.fn.countryCollection.push(element);
                });
            }
        }
    });
 }
 FetchCountries();
}

ko.applyBindings(new viewmodel());
my view(.cshtml)
       <h2>Cascading DropDown using Knockout</h2>
     FirstName:
       <input type="text" id="txtFirstName" name="txtFirstName" data- 
        bind="value:Employee.FirstName" />
        <br />
        LastName:
       <input type="text" id="txtLastName" name="txtFirstName" data-   
        bind="value:Employee.LastName" />
        <br />
       Country Name:
   <select data-bind="options: fn.countryCollection, optionsCaption: 'Choose country...',
    optionsValue: function (item) { return item.CountryId; },
    optionsText: function (item) { return item.CountryName; }, value: Employee.Country,
    valueUpdate: 'change'"
    id="Country" name="Country">
    </select>
    <br />

    State Name:
     <select data-bind="options: fn.stateCollection, optionsCaption: 'Choose state...',
      optionsValue: function (item) { return item.StateId; },
        optionsText: function (item) { return item.StateName; },  value: Employee.State,
        valueUpdate: 'change'"
        id="State" name="State">
      </select>
       <br />

      City Name:
     <select data-bind="options: fn.cityCollection, optionsCaption: 'Choose city...',
      optionsValue: function (item) { return item.CityId; },
       optionsText: function (item) { return item.CityName; }, value: Employee.City,
     valueUpdate: 'change'"
     id="City" name="City">
    </select>

    <input type="button" data-bind="click: submit" value="Submit" id="btnSubmit" />

Need Your Help

How to delete all data from all tables in Rails?

ruby-on-rails activerecord

I can do Post.delete_all to delete all my posts, but what if I want to delete all posts, comments, blogs, etc.?

Wi-Fi Direct Group Owner Frequency Band

android wifi android-wifi wifi-direct wificonfiguration

I'm currently using a Nexus 10 (2.4 GHz and 5 GHz dual band radio) to connect to a third-party peripheral device (2.4GHz single band radio) via Wi-Fi Direct. When I connect the tablet as a Client, ...