作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
阅读ASP.NET MVC 2 in Action和观看Jimmy Bogard's presentation from MvcConf(强烈推荐!)之后,我开始实现他们的一些想法。
他们要做的很酷的事情之一,不仅是使用AutoMapper将您的实体映射到某些 View 模型,还可以使用AutoMapViewResult将其自动化:
public class EventsController : BaseController
{
public ActionResult Show(Event id) // EntityModelBinder gets Event from repository
{
return AutoMapView<EventsShowModel>(id); // AutoMapView<T>(model) is a helper method on the BaseController, that calls AutoMapViewResult<T>(...)
}
}
// not exactly what you'll find in the book, but it also works :-)
public class AutoMapViewResult<TDestination> : ViewResult
{
public AutoMapViewResult(string viewName, string masterName, object model)
{
ViewName = viewName;
MasterName = masterName;
ViewData.Model = Mapper.Map(model, model.GetType(), typeof(TDestination));
}
}
Edit
的
EventsEditModel
Action :
public class EventsEditModel
{
// ... some properties ...
public int LocationId { get; set; }
public IList<SelectListItem> Locations { get; set; }
}
public class EventsController : BaseController
{
public ActionResult Edit(Event id)
{
return AutoMapView<EventsEditModel>(id);
}
}
EventsEditModel
的
Locations
属性获取位置的最佳方法是什么?
AutoMapViewResult
和许多不同的entity-viewmodel组合。
最佳答案
(自从我看了这篇演讲之后)我还没有到达需要的时候,但是我想到了一个可能的解决方案。我认为创建一个属性,指定需要加载此属性将是可行的。我将从一个抽象类开始:
public abstract class LoadDataAttribute : Attribute
{
public Type Type { get; set; }
protected LoadDataAttribute(Type type)
{
Type = type;
}
public abstract object LoadData();
}
public class LoadLocationsAttribute : LoadDataAttribute
{
public LoadLocationsAttribute() : base(typeof(IList<SelectListItem>))
public override object LoadData()
{
// get locations and return IList<SelectListItem>
}
}
ExecuteResult
的
AutoMappViewResult
中,您会找到所有带有
LoadDataAttribute
的属性,调用
LoadData()
,将其强制转换为属性中指定的类型,并将其分配给该属性。
IList<SelectListItem>
而不是
object
,从而省去了一些转换方面的麻烦。
public class EventsEditModel
{
// ... some properties ...
public int LocationId { get; set; }
[LoadLocations]
public IList<SelectListItem> Locations { get; set; }
}
关于asp.net-mvc - 使用AutoMapper/AutoMapViewResult时如何将下拉列表的数据获取到ViewModel中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3507466/
我是一名优秀的程序员,十分优秀!