【问题标题】:issue while submitting cascading dropdown using knockout使用敲除提交级联下拉列表时出现问题
【发布时间】:2014-04-13 18:12:27
【问题描述】:

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

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

【问题讨论】:

    标签: jquery asp.net-mvc-3 knockout.js


    【解决方案1】:

    当您使用淘汰赛时,请尽可能多地使用 ko。例如,您可以订阅 country observable,而不是使用 jquery on change。其次,您应该在点击时使用点击绑定而不是 jquery。也不需要多个 applyBindings。

    所以你的视图模型将是这样的:-

    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());
    

    我的看法(.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" />
    

    【讨论】:

    • 感谢您再次回复.. 仍然我没有得到输出.. 所以我还附上了以下 cshtml 代码.. 还有一件事我也无法从 thii 代码中获取下拉值,请帮助我
    • 未捕获的错误:无法解析绑定。消息:ReferenceError:FirstName 未定义;绑定值:value:FirstName
    • 好的..我无法获得下拉数据..只有我得到的国家列表没有获得州和城市..实际上我的要求是使用敲除从数据库中获取数据到下拉列表。在我之后想将更改作为注册表单提交到数据库,我已经附加了模型类和控制器,以及我如何从数据库中获取数据到所有附加的下拉列表..请帮助我
    • 如果可能的话,我会为你提供完整的解决方案。如果你好,请告诉我..并帮助我
    • 现在我正在获取下拉值..唯一的是我需要提交这些值。但我无法触发动作方法..
    猜你喜欢
    • 1970-01-01
    • 2014-04-14
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多