Example #05: Mapping techniques1. Creating our mapping:
private static void CreateMaps()
{
GridModelMapper.CreateSimpleMappingAsNeeded = true;
// If you set CreateSimpleMappingAsNeeded to true...
// you dont need to specify the following mapping, but
// pay attention, *Product must not have nested unmapped classes*
// the mappings will be created dymicaly
// Mapper.CreateMap<Product, ProductModel>();
// for simple maps like this, the GMM should be enought
GridModelMapper.CreateMap<Category, CategoryModel>();
// GMM and AM can work together, the mappings are not overriden by each other
Mapper.CreateMap<Order, OrderModel>()
.ForMember(trg => trg.Id, opt => opt.MapFrom(src => src.OrderID))
.ForMember(trg => trg.RecipientName, opt => opt.MapFrom(src => src.ShipName))
.ForMember(trg => trg.RecipientAddress,
opt => opt.MapFrom(src => src.ShipAddress))
.ForMember(trg => trg.RecipientCity, opt => opt.MapFrom(src => src.ShipCity));
GridModelMapper.CreateMap<Order, OrderModel>()
.MapProperty(entity => entity.Customer.ContactName,
viewModel => viewModel.Customer.CustomerName)
.MapProperty(entity => entity.Employee.LastName,
viewModel => viewModel.Employee.EmployeeName)
.MapProperty(entity => entity.Shipper.CompanyName,
viewModel => viewModel.Shipper.CompanyName);
// Continuing to map the associations of our entities
Mapper.CreateMap<Customer, CustomerModel>()
.ForMember(trg => trg.CustomerName, opt => opt.MapFrom(src => src.ContactName));
Mapper.CreateMap<Employee, EmployeeModel>()
.ForMember(trg => trg.EmployeeName, opt => opt.MapFrom(src => src.LastName));
Mapper.CreateMap<Shipper, ShipperModel>()
.ForMember(trg => trg.CompanyName, opt => opt.MapFrom(src => src.CompanyName));
}
2. Here we can send our view to the client, no need to pass any data yet.
public ActionResult MappingTechniques()
{
return View();
}
3. And then send the data through ajax requests.
[ApplyTransaction, GridAction(EnableCustomBinding = true)]
public ActionResult MappingTechniquesData(GridCommand command)
{
var query = NHibernateHelper.CurrentSession.Query<Order>();
var gridHelper = new GridCustomBindingHelper<Order, OrderModel>(command, query);
var gridModel = gridHelper.BuildGridModel();
return View(gridModel);
}
4. Finaly, the Grid configuration
@(Html.Telerik().Grid<OrderModel>().Name("Grid")
.Columns(columns =>
{
columns.Bound(d => d.Id).Width(80);
columns.Bound(d => d.RecipientName);
columns.Bound(d => d.RecipientAddress);
columns.Bound(d => d.RecipientCity);
columns.Bound(d => d.Customer.CustomerName);
columns.Bound(d => d.Employee.EmployeeName);
columns.Bound(d => d.Shipper.CompanyName);
})
.EnableCustomBinding(true).Sortable().Filterable().Groupable()
.Pageable(x => x.PageSize(15))
.DataBinding(dataBinding => dataBinding.Ajax()
.Select<ExamplesController>(ctr => ctr.MappingTechniquesData(null))))