将模型属性映射到控制器

时间:2012-03-10 21:27:02

标签: c# model-view-controller model properties mapping

我整天搜索了我的问题的解决方案,但没有找到任何可接受的......

我的项目是使用MVC模式构建的,我不确定是否可以直接访问视图的模型。据我所知,它旨在从视图中“隐藏”模型,并将控制器用作“代理”。

我向您展示了一个更好地理解我的问题的例子。

模特:

internal class ExampleModel 
{
    public Size GridSize {get; set;}
    //a lot more properties
    //...
    //business logic
}

控制器:

internal class ExampleController 
{
    private ExampleModel m_Model;

    //Logic "proxy" with some extensions
    //A lot of functions
    //--------------------
    //Mapping the model's properties
    public Size GridSize 
    {
        get
        {
            return m_Model.GridSize;
        }
        set
        {
            m_Model.GridSize = value;
        }
    }
    //A lot more properties, mapping the ones from the model
}

所以我的问题是:如何将模型的属性自动映射到控制器?因为“同步”模型和控制器之间的属性......很糟糕? :P 或者我可以公开m_Model吗?我真的不知道该怎么办..

提前致谢:)

2 个答案:

答案 0 :(得分:1)

通常,您可以将模型传递到视图中,以便在控制器操作中将其返回。

public class HomeController
{
   public ActionResult Index()
   {
      // Do something with model here, in this example we are creating a new model
      var model = new Model(); 

      // Send the model to the view, this is then available as @Model
      return View(model);
   }
}

请注意,您的视图可能还有其他属性,您不希望使用该模型对模型进行轮询。在这种情况下,您可以创建一个视图模型,该模型使用其他属性扩充模型。您的视图模型通常包含对模型的引用。

有些纯粹主义者不喜欢将模型暴露给视图,因此此链接提供了一些其他方法:

http://blogs.msdn.com/b/simonince/archive/2010/01/26/view-models-in-asp-net-mvc.aspx

答案 1 :(得分:0)

devdigital的answer是正确的,你不应该通过控制器暴露你的模型(在设计方面,它会迫使你的View了解控制器的某些信息......)。 您的Controller应该准备View所需的所有数据,并在创建ViewResult时传递它(这是return View(model)对默认View名称的作用)。

但是,您还询问是否有更好的方法来映射对象之间的属性。我不认为devdigital的链接提到了这个特殊工具(但确实提到了映射器):AutoMapper(http://automapper.codeplex.com/)。

首先在2个实体/模型/对象之间配置任何类型的Map。默认行为只是分配具有相同名称的属性,但您可以配置为忽略属性,或自定义值赋值。

AutoMapper.Mapper.CreateMap<ExampleEntity, ExampleModel>();

然后你就用它......

ExampleModel model = AutoMapper.Mapper.Map<ExampleModel>(myEntity);

这适用于1:1实体映射。如果您实际上是在扩充ViewModel,我建议不要使用AutoMapper(ViewModel就是您用来提供来自不同实体或来源的数据的视图)。