Cascading DropDown in MVC4 Using Knockout With Web API and Entity Framework en C#, HTML para Visual Studio 2012 PDF
Cascading DropDown in MVC4 Using Knockout With Web API and Entity Framework en C#, HTML para Visual Studio 2012 PDF
Saber ms
Developer Network
Tecnologas
Iniciar sesin
Descargas
Programas
Comunidad
Documentacin
Suscripciones a MSDN
Obtener herramientas
Ejemplos
Microsoft Developer Network > Ejemplos > Cascading DropDown in MVC4 using Knockout with Web API and Entity Framework
Acceso rpido
Mis muestras
Cargar un ejemplo
Examinar solicitudes de ejemplos
Descargar
2,804
Puntos
Superior 5%
C# 2,8 MB
Clasificaciones
Descargado
ltima actualizacin
20/02/2014
1.033 veces
Licencia
Favoritos
Agregar a favoritos
Compartir
Necesita
Traducido al
English
Tecnologas
C#, Windows 7, jQuery, Entity Framework, .NET Framework 4.5, knockout.js, MVC5, ASP.NET Web API 2
Temas
Cascading DropDown in MVC, Web API in MVC, How to use Knockout in MVC, How to user Data Transfer Object
Mostrar actividad
Descripcin
Explorar cdigo
PyR
Introduction
In this article I am going to explore many things like dropdown cascading, how to use entity framework and how to use data
transfer object with entity framework and how to create web API and fetch data using web API and display using knockout.
Description
Web API The ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients,
including browsers and mobile devices. The ASP.NET Web API is an ideal platform for building REST applications on the .NET
Framework.
Knockout Knockout is a JavaScript library that helps you to create rich, responsive displays and editor user interfaces with a
clean underlying data model. Read more herehttp://knockoutjs.com/.
Entity Framework Entity Framework EF is an objectrelational mapper that enables .NET developers to work with relational
data using domainspecific objects. It eliminates the need for most of the dataaccess code that developers usually need to
write.
Data Transfer Objects Data Transfer Objects are reusable classes that contain related data and no business logic. They may be
defined on the service side, client side, or both sides of the communication channel. Their properties i.e. getters/setters may
wrap primitive data types e.g. integers, strings, etc. or other DTOs.
This is my database schema which is used in this sample:
Image 1.
As you all know when we use entity framework it build default models classes and context classes, So we are going to use data
transfer object besides using entity framework models and context classes.
So first of all add data transfer object model classes:
C#
publicclassCountryDTO
{
publicintCountryId{get;set;}
publicstringCountryName{get;set;}
}
publicclassStateDTO
{
publicintStateId{get;set;}
publicintCountryId{get;set;}
publicstringStateName{get;set;}
}
publicclassCityDTO
{
publicintStateId{get;set;}
publicintCityId{get;set;}
publicstringCityName{get;set;}
}
publicstaticList<CountryDTO>LCountriesToCountryDTO(List<Countries>e)
{
List<CountryDTO>lstCountryDTO=e.Select(
country=>newCountryDTO()
{
CountryId=country.CountryId,
CountryName=country.CountryName
}).ToList();
returnlstCountryDTO;
}
publicstaticStateDTOStatesToStateDTO(Statese)
{
returnnewStateDTO
{
StateId=e.StateId,
StateName=e.StateName
};
}
publicstaticList<StateDTO>LStatesToStateDTO(List<States>e)
{
List<StateDTO>lstStateDTO=e.Select(
state=>newStateDTO()
{
StateId=state.StateId,
StateName=state.StateName
}).ToList();
returnlstStateDTO;
}
publicstaticCityDTOCitiesToCityDTO(Citiese)
{
returnnewCityDTO
{
CityId=e.CityId,
CityName=e.CityName
};
}
publicstaticList<CityDTO>LCitiesToCityDTO(List<Cities>e)
{
List<CityDTO>lstCityDTO=e.Select(
city=>newCityDTO()
{
CityId=city.CityId,
CityName=city.CityName
}).ToList();
returnlstCityDTO;
}
}
publicList<StateDTO>GetStates(intcountryId)
{
using(TestDBEntitiesdbcontext=newTestDBEntities())
{
varlstStates=dbcontext.States.Where(b=>b.CountryId==countryId).ToList();
List<StateDTO>list=newList<StateDTO>();
list=Converter.LStatesToStateDTO(lstStates.ToList());
returnlist;
}
}
publicList<CityDTO>GetCities(intstateId)
{
using(TestDBEntitiesdbcontext=newTestDBEntities())
{
varlstCities=dbcontext.Cities.Where(b=>b.StateId==stateId).ToList();
List<CityDTO>list=newList<CityDTO>();
list=Converter.LCitiesToCityDTO(lstCities.ToList());
returnlist;
}
}
}
Repository interface:
C#
publicinterfaceILocationRepository
{
List<CountryDTO>GetCountries();
List<StateDTO>GetStates(intcountryId);
List<CityDTO>GetCities(intstateId);
}
Image 2.
//GETapi/<controller>
publicIEnumerable<CountryDTO>GetCountries()
{
//returnnewstring[]{"value1","value2"};
returnrepository.GetCountries();
}
//GETapi/<controller>/5
[ActionName("GetStates")]
publicIEnumerable<StateDTO>GetStates(intid)
{
returnrepository.GetStates(id);
}
//GETapi/<controller>/5
[ActionName("GetCities")]
publicIEnumerable<CityDTO>GetCities(intid)
{
returnrepository.GetCities(id);
}
//POSTapi/<controller>
publicvoidPost([FromBody]stringvalue)
{
}
//PUTapi/<controller>/5
publicvoidPut(intid,[FromBody]stringvalue)
{
}
//DELETEapi/<controller>/5
publicvoidDelete(intid)
{
}
}
config.Routes.MapHttpRoute(
name:"DefaultApiWithAction",
routeTemplate:"api/{controller}/{action}/{id}",
defaults:new{id=RouteParameter.Optional}
);
}
Here we are done with model and controller part, Now time to work in view part.
HTML
@{
ViewBag.Title="CascadingDropDownusingKnockout/WebAPISample";
}
<scriptsrc="~/Scripts/jquery1.8.2.min.js"></script>
<scriptsrc="~/Scripts/knockout2.2.0.js"></script>
<scripttype="text/javascript">
$(document).ready(function(){
FetchCountries();
$("#Country").change(function(){
varcountryId=$("#Country").val();
$.ajax({
type:"GET",
url:"http://localhost:62830/api/Location/GetStates/"+countryId,
contentType:"application/json;charset=utf8",
dataType:"json",
success:function(response){
if(response!=""){
$(response).each(function(index,element){
viewModel.stateCollection.push(element);
});
ko.applyBindings(viewModel);
}
}
});
});
$("#State").change(function(){
varstateId=$("#State").val();
$.ajax({
type:"GET",
url:"http://localhost:62830/api/Location/GetCities/"+stateId,
contentType:"application/json;charset=utf8",
dataType:"json",
success:function(response){
if(response!=""){
$(response).each(function(index,element){
viewModel.cityCollection.push(element);
});
ko.applyBindings(viewModel);
}
}
});
});
});
functionFetchCountries(){
viewModel={
countryCollection:ko.observableArray(),
stateCollection:ko.observableArray(),
cityCollection:ko.observableArray()
};
$.ajax({
type:"GET",
url:"http://localhost:62830/api/Location",
contentType:"application/json;charset=utf8",
dataType:"json",
success:function(response){
if(response!=""){
$(response).each(function(index,element){
viewModel.countryCollection.push(element);
});
ko.applyBindings(viewModel);
}
}
});
}
</script>
<h2>CascadingDropDownusingKnockout/WebAPISample</h2>
CountryName:<selectdatabind="options:countryCollection,optionsCaption:'Choosecountry...',
optionsValue:function(item){returnitem.CountryId;},
optionsText:function(item){returnitem.CountryName;},value:Country,
valueUpdate:'change'"id="Country"name="Country"></select>
<br/>
StateName:<selectdatabind="options:stateCollection,optionsCaption:'Choosestate...',
optionsValue:function(item){returnitem.StateId;},
optionsText:function(item){returnitem.StateName;},value:State,
valueUpdate:'change'"id="State"name="State"></select>
<br/>
CityName:<selectdatabind="options:cityCollection,optionsCaption:'Choosecity...',
optionsValue:function(item){returnitem.CityId;},
optionsText:function(item){returnitem.CityName;},value:City,
valueUpdate:'change'"id="City"name="City"></select>
Image 3.
Image 4.
Image 5.
Image 6.
Centros de desarrollo
Recursos de aprendizaje
Comunidad
Soporte tcnico
Windows
Foros
Autosoporte
Channel 9
Blogs
Office
MSDN Magazine
Codeplex
Visual Studio
Microsoft Azure
Programas
BizSpark para nuevas empresas
DreamSpark
Ms...
Espaa Espaol
Imagine Cup
Boletn
Privacidad y cookies
Trminos de uso
Marcas comerciales
2016 Microsoft