gpt4 book ai didi

c# - Models 和 ViewModels 应该如何交互?

转载 作者:太空宇宙 更新时间:2023-11-03 13:48:46 24 4
gpt4 key购买 nike

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

这是场景:

我加载一个基于 CustomerModel 的 View ,这个 View 有一个表单。当表单被提交时,CustomerModel 被传递给 Action,比方说,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
}

鉴于我在之前的一篇文章中读到我应该避免同时使用模型类,数据和 View 模型,我问:

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

最佳答案

How does the interaction between Model and ViewModels should be?

View 模型向 View 描述数据。它用于表示逻辑并向 View 提供数据。这些模型用于描述来自您的数据源(例如 sql 或文件)的数据。

View 模型中的内容示例:

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 或普通的旧构造函数注入(inject)。

例如构造函数注入(inject)

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();
}
}

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

关于c# - Models 和 ViewModels 应该如何交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14365796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com