Jquery 使用knockout提交级联下拉列表时出现问题

Jquery 使用knockout提交级联下拉列表时出现问题,jquery,asp.net-mvc-3,knockout.js,Jquery,Asp.net Mvc 3,Knockout.js,我已经使用knockoutjs创建了一个级联下拉列表,即我从数据库中检索数据,并使用knockout绑定到下拉列表。现在我在向数据库提交数据时卡住了,如何使用knockout向数据库提交数据: <script src="~/Scripts/jquery-1.8.2.min.js"></script> <script src="~/Scripts/knockout-2.2.0.js"></script>

我已经使用knockoutjs创建了一个级联下拉列表,即我从数据库中检索数据,并使用knockout绑定到下拉列表。现在我在向数据库提交数据时卡住了,如何使用knockout向数据库提交数据:

         <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;
        }
    }
    }

$(文档).ready(函数(){
国家();
$(“#国家”)。更改(功能(){
var countryId=$(“#Country”).val();
$.ajax({
键入:“获取”,
url:“http://localhost:62830/api/Location/GetStates/“+countryId,
contentType:“应用程序/json;字符集=utf-8”,
数据类型:“json”,
成功:功能(响应){
如果(响应!=“”){
$(响应)。每个(函数(索引、元素){
viewModel.stateCollection.push(元素);
});
应用绑定(视图模型);
}
}
});
});
$(“#状态”)。更改(函数(){
var stateId=$(“#State”).val();
$.ajax({
键入:“获取”,
url:“http://localhost:62830/api/Location/GetCities/“+stateId,
contentType:“应用程序/json;字符集=utf-8”,
数据类型:“json”,
成功:功能(响应){
如果(响应!=“”){
$(响应)。每个(函数(索引、元素){
viewModel.cityCollection.push(元素);
});
应用绑定(视图模型);
}
}
});
});
函数(国){
视图模型={
countryCollection:ko.observableArray(),
stateCollection:ko.observableArray(),
城市集合:ko.observearray()
};
$.ajax({
键入:“获取”,
url:“http://localhost:62830/api/Location",
contentType:“应用程序/json;字符集=utf-8”,
数据类型:“json”,
成功:功能(响应){
如果(响应!=“”){
$(响应)。每个(函数(索引、元素){
viewModel.countryCollection.push(元素);
});
应用绑定(视图模型);
}
}
});
}
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;
警报(myVar2)
函数viewmodel(){
var Employee={};
Employee.FirstName=ko.observable(),
Employee.LastName=ko.observable(),
Employee.countryCollection=myVar,
Employee.stateCollection=myVar1,
Employee.cityCollection=myVar2
}
$('#btnSubmit').live(“单击”,函数(e){
$.ajax({
url:“/Home/Submit/”,
async:true,
cache:false,
键入:“post”,
数据:ko.toJSON(viewmodel),
contentType:'应用程序/json',
成功:功能(结果){
}
});
});
});
使用Knockout的级联下拉列表
名字:

姓氏:
国家名称:
州名:
城市名称:`在此处输入代码` **控制器类:** [HttpPost] 公共操作结果提交(对象绑定) { 字符串fname=Request.Form[“txtfirstName”]; 字符串lname=Request.Form[“txtlastName”]; 返回视图(); } 模型类: 公共类城市旅游 { public int StateId{get;set;} public int CityId{get;set;} 公共字符串CityName{get;set;} } 公共类国家 { public int CountryId{get;set;} 公共字符串CountryName{get;set;} } 公共类声明 { public int StateId{get;set;} public int CountryId{get;set;} 公共字符串StateName{get;set;} } 公共静态类转换器 { //公共静态国家/地区CountryDTOTOCountries(CountryDToD) //{ //返回新的国家 // { //CountryId=d.CountryId, //CountryName=d.CountryName // }; //} 公共静态国家/地区至国家/地区至国家/地区(待定国家/地区e) { 返回新国家/地区 { CountryId=e.CountryId, CountryName=e.CountryName }; } 公共静态列表LCountriesToCountryDTO(列表e) { 列出lstcontrydto=e。选择( country=>new CountryDTO() { CountryId=country.CountryId, CountryName=country.CountryName }).ToList(); 返回lstcontrydto; } 公共静态状态到状态到状态(TBL状态e) { 将新状态返回到 { StateId=e.StateId, StateName=e.StateName }; } 公共静态列表LStatesToStateDTO(列表e) { 列出lstStateDTO=e。选择( state=>newstatedto() { StateId=state.StateId, StateName=state.StateName }).ToList(); 返回lsstatedto; } 公共静态城市到城市到城市到城市(待定) { 返回新城市到 { CityId=e.CityId, CityName=e.CityName }; } 公共静态列表LCitiesToCityDTO(L
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());
       <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" />