Sunteți pe pagina 1din 7

Al usar este sitio acepta el uso de cookies para anlisis, contenido personalizado y publicidad.

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

Descargue Visual Studio

Acceso rpido

Cascading DropDown in MVC4 using


Knockout with Web API and Entity Framework
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.Getting Started Create a new Project

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

Licencia de Apache, versin 2.0

Favoritos

Agregar a favoritos

Compartir

Necesita

Visual Studio 2012 , Knockout MVC ,


BasicWebApi , Microsoft Visual Studio 2012
SDK , ASP.NET Web Forms MVC 4

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

Raj Kumar Beniwal


Se uni Apr 2013
Ver ejemplos
1

Mostrar actividad

Notificar abuso a Microsoft

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.

Building the Sample


Getting Started
Create a new Project. Open Visual Studio 2012.
Go to File => New => Project.
Select Web in installed templates.
Select ASP.NET MVC 4 Web Application.
Enter the Name and choose the location.
Click OK.

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

Now add a convertor class:


C#
publicstaticclassConverter
{
publicstaticCountryDTOCountriesToCountryDTO(Countriese)
{
returnnewCountryDTO
{
CountryId=e.CountryId,
CountryName=e.CountryName
};
}

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

Here is my repository class:


C#
publicclassLocationRepository:ILocationRepository
{
publicList<CountryDTO>GetCountries()
{
using(TestDBEntitiesdbcontext1=newTestDBEntities())
{
varlstCountries=fromrindbcontext1.Countriesselectr;
List<CountryDTO>lst=newList<CountryDTO>();
lst=Converter.LCountriesToCountryDTO(lstCountries.ToList());
returnlst;
}
}

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

Now add Web API controller class:


Image 2.

This is my controller class code:


C#
publicclassLocationController:ApiController
{
staticreadonlyILocationRepositoryrepository=newLocationRepository();

//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)
{
}
}

To stop method confliction we have added ActionName in two methods.


Now add this routing in WebApiConfig class:
C#
publicstaticvoidRegister(HttpConfigurationconfig)
{
config.Routes.MapHttpRoute(
name:"DefaultApi",
routeTemplate:"api/{controller}/{id}",
defaults:new{id=RouteParameter.Optional}
);

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>

All set. Now run the application:

Image 3.

Image 4.

Image 5.

Image 6.

Source Code Files


CascadingDropDownMVCWebAPISQLData.zip

Centros de desarrollo

Recursos de aprendizaje

Comunidad

Soporte tcnico

Windows

Microsoft Virtual Academy

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

S-ar putea să vă placă și