Skip to content

Instantly share code, notes, and snippets.

[AutoMap(typeof(ViewModel)]
public ActionResult View(int id)
{
var entity = LoadFromDatabase(id);
return View(entity);
}
public ActionResult View(int id)
{
var entity = LoadFromDatabase(id);
var viewModel = Mapper.Map<ViewModel>(entity);
return View(viewModel);
}
public ActionResult View(User entity) {
UserEditModel model = //change entity into a edit model
return View(model);
}
ModelMetadata modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());
ModelValidator compositeValidator = ModelValidator.GetModelValidator(modelMetadata, controllerContext);
foreach (ModelValidationResult result in compositeValidator.Validate(null))
bindingContext.ModelState.AddModelError(ValidationPropertyName, result.Message);
foreach (var child in destination)
{
if (!source.Any(sourceTarget => destIdProperty.GetValue(child, null).Equals(idProperty.GetValue(sourceTarget, null))))
{
destination.Remove(child);
}
}
foreach (var child in source.ChildCollection)
{
var targetChild = target.ChildCollection.SingleOrDefault(c => c.Equals(child)); //overwrite Equals or replace comparison with an Id comparison
if (targetChild == null) target.ChildCollection.Add(Mapper.Map<SourceChildType, TargetChildType>(child)); else Mapper.Map(child, targetChild);
}
public class PaginationMapper : IObjectMapper
{
private IMappingEngineRunner _mapper;
public T Map<T>(object source)
{
TypeMap typeMap = _mapper.ConfigurationProvider.FindTypeMapFor(source, source.GetType(), typeof(T));
MappingOperationOptions mappingOperationOptions = new MappingOperationOptions();
ResolutionContext resolutionContext = new ResolutionContext(typeMap, source, source.GetType(), typeof(T), mappingOperationOptions);
return (T)_mapper.Map(resolutionContext);
}
[AutoMap(typeof(EventListViewModel))]
public ActionResult Index(int? page)
{
page = page ?? 1;
var entities = //load data from database
.AsPagination(page.Value, 20); //pagination method from MVC Contrib
return View(entities);
}
var _dependencyResolver = DependencyResolver.Current; //Get this from private variable that you can override when unit testing
routes.MapRoute(
"Countries",
"countries/{country}",
new {
controller = "Countries",
action = "Index"
},
new {
public class InjectedRouteConstraint<T> : IRouteConstraint where T : IRouteConstraint
{
private IDependencyResolver _dependencyResolver { get; set; }
public InjectedRouteConstraint(IDependencyResolver dependencyResolver)
{
_dependencyResolver = dependencyResolver;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{