gpt4 book ai didi

c# - 在 ASP.Net MVC 的 View 模型中验证嵌套模型

转载 作者:行者123 更新时间:2023-11-30 12:29:13 25 4
gpt4 key购买 nike

我有一个带有公司模型的应用程序。公司模型具有到地址模型的导航属性(一对一关系):

Company.cs

public class Company
{
public int CompanyID { get; set; }
public string Name { get; set; }

// Snip...

public virtual Address Address { get; set; }
}

我已经创建了一个 View 模型来处理编辑、细节和创建操作:

CompanyViewModel.cs

public class CompanyViewModel
{
public int CompanyID { get; set; }

[Required]
[StringLength(75, ErrorMessage = "Company Name cannot exceed 75 characters")]
public string Name { get; set; }

// Snip...

public Address Address { get; set; }
}

我在 Controller 中使用 AutoMapper 在模型和 View 模型之间来回映射,一切正常。但是,我现在想对地址对象使用验证 - 我不希望在没有地址的情况下创建公司。

我的第一个想法是简单的路线 - 我尝试在 Address 属性上放置一个“[Required]”注释。这没有做任何事情。

然后我认为最好取消 Address 属性并在 View 模型中抽象该数据,因此我为我的 Address 类中的所有属性向 View 模型添加了属性:

public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
// etc....

这似乎是个好习惯,但现在我的 AutoMapper 无法将这些属性映射到 Company 类的 Address 对象,所以我不得不在 Controller 中手动映射:

public ActionResult Details(int id = 0)
{
// Snip code retrieving company from DB

CompanyViewModel viewModel = new CompanyViewModel();
viewModel.Name = company.Name;
viewModel.Address1 = company.Address.Address1;

// Snip...

return View(viewModel);
}

这导致我的 Controller 中有很多额外的代码,而不是一个很好的单行 AutoMapper 语句...那么处理这个问题的正确方法是什么(在 View 模型中验证嵌套模型)?

直接在 View 模型中公开 Address 属性是好的做法,还是像我所做的那样用单独的属性将其抽象出来更好?

AutoMapper 能否在源和目标不完全匹配的情况下工作?

最佳答案

如果您希望自动映射器能够在不明确指定映射的情况下将您的属性从模型映射到您的 View 模型,您必须使用“展平约定”:意味着您必须将导航属性的名称与其属性名称连接起来.

所以你的 ViewModel 应该包含

public int CompanyID { get; set; }

[Required]
[StringLength(75, ErrorMessage = "Company Name cannot exceed 75 characters")]
public string Name { get; set; }

// Snip...
//Address is the navigation property in Company, Address1 is the desired property from Address
public string AddressAddress1 { get; set; }
public string AddressAddress2 { get; set; }
public string AddressCity { get; set; }
public string AddressPostalCode { get; set; }
}

顺便说一句,您还可以告诉 AutoMapper 映射不明确遵守命名约定的属性:

Mapper.CreateMap<Company, CompanyViewModel>()
.ForMember(dest => dest.Address1, opt => opt.MapFrom(src => src.Address.Address1));

关于c# - 在 ASP.Net MVC 的 View 模型中验证嵌套模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19162593/

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