ViewModel模型应该如何交互?

时间:2013-01-16 19:05:03

标签: c# asp.net-mvc model viewmodel

Model和ViewModels之间的交互应该如何? 假设我有一个名为Customer with Id and Email properties的类,另一个CustomerModel具有相同的属性。

这是情景:

我加载了一个基于CustomerModel的视图,这个视图有一个表单。提交表单后,CustomerModel将传递给Action,例如Save。在Save操作中,我应该创建Customer实例并按属性填充它吗?

以下示例:

ActionResult Save(CustomerModel cm)
{
   //validation goes here

   Customer c = new Customer();
   c.Id = cm.Id;
   c.Email = cm.Email;

   context.Entry<Customer>(c).State = System.Data.EntityState.Modified;
   context.SaveChanges();

   //continue
  }

鉴于我在之前的帖子中读到我应该避免将模型类用于两个目的,数据和视图模型,我问:

这是实施它的正确方法吗?

1 个答案:

答案 0 :(得分:1)

  

Model和ViewModel之间的交互应该如何?

视图模型向视图描述数据。它用于表示逻辑并为视图提供数据。这些模型用于描述数据源中的数据,如sql或文件。

视图模型中的内容示例:

public class CustomerViewModel
{
    public long Id { get; set; }
    public bool IsFoundingMember { get { return Id < 1000; } }
    public string Name { get; set; }
    public bool IsABaggins { get { return !string.IsNullOrWhiteSpace(Name) ? Name.EndsWith("Baggins") : false; } }
}

模型中的内容示例

public class Customer
{
    public long? Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public DateTime? DateOfBirth { get; set; }
}

我会尝试将逻辑分组为可维护性的函数。

说:

ActionResult Save(CustomerModel cm)
{
   if(!ValidateCustomerModel(cm))
   {
        //Deal with invalid data
   }

   UpdateCustomer(cm);

   //continue
}

public bool ValidateCustomerModel(CustomerModel model)
{
    //Do stuff
    return true;
}

public void UpdateCustomer(CustomerModel model)
{
   Customer c = new Customer();
   c.Id = cm.Id;
   c.Email = cm.Email;

   context.Entry<Customer>(c).State = System.Data.EntityState.Modified;
   context.SaveChanges();
}

将所有CRUD逻辑分离出来后,您可以为该逻辑创建一些类,并查看Unity,Ninject或普通的构造函数注入。

e.g。构造函数注入

public class MyController : Controller
{
    private readonly ICustomerDL _customerDL;
    public MyController(ICustomerDL customerDL)
    {
        _customerDL = customerDL;
    }

    //Load your implementation into the controller through the constructor
    public MyController() : this(new CustomerDL()) {}

    ActionResult Save(CustomerModel cm)
    {
       if(!ValidateCustomerModel(cm))
       {
            //Deal with invalid data
       }

       _customerDL.UpdateCustomer(cm);

       //continue
    }

    public bool ValidateCustomerModel(CustomerModel model)
    {
        //Do stuff
        return true;
    }
}

public interface ICustomerDL
{
    void UpdateCustomer(CustomerModel model);
}

public class CustomerDL : ICustomerDL
{
    public void UpdateCustomer(CustomerModel model)
    {
       Customer c = new Customer();
       c.Id = cm.Id;
       c.Email = cm.Email;

       context.Entry<Customer>(c).State = System.Data.EntityState.Modified;
       context.SaveChanges();
    }
}

好处是您的所有逻辑都将是清洁和结构化的,这将使单元测试和代码维护变得轻而易举。