我使用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;
}
}
}
答案 0 :(得分:1)
当您使用淘汰赛时,尽可能多地使用ko。例如,不是在更改时使用jquery,而是可以订阅country observable。其次,你应该在点击时使用点击绑定jquery。也不需要多个applyBinding。
所以你的视图模型会是这样的: -
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" />