我没有任何其他方式来描述它,那么我是如何在标题中做到的。由构造函数链接到数据模型的视图模型
我有一个看起来像这样的视图模型:
public class CreateArtistModel
{
public IEnumerable<SelectListItem> Cultures { get; set; }
public IEnumerable<SelectListItem> Products { get; set; }
public Artists Artist { get; internal set; }
/// <summary>
/// Default constructor
/// </summary>
public CreateArtistModel() { }
/// <summary>
/// Non-default constructor with 1 parameter, culturelist
/// </summary>
/// <param name="cultures">List that can contain all the possible cultures.</param>
/// <param name="products">List that can contain all possible products.</param>
public CreateArtistModel(IEnumerable<SelectListItem> cultures, IEnumerable<SelectListItem> products) { Cultures = cultures; Products = products; }
/// <summary>
/// Non-default constructor that can have 1 parameter, artist
/// </summary>
/// <param name="artist">The artist with its various properties</param>
public CreateArtistModel(Artists artist) { Artist = artist; }
/// <summary>
/// Non-default constructor that can have 2 parameter, a list cultureList and an atist
/// </summary>
/// <param name="cultures">List that can contain all the possible cultures.</param>
/// <param name="products">List that can contain all possible products.</param>
/// <param name="artist">The artist with its various properties</param>
public CreateArtistModel(IEnumerable<SelectListItem> cultures, IEnumerable<SelectListItem> products, Artists artist)
{
Cultures = cultures;
Products = products;
Artist = artist;
}
[Required(ErrorMessage = "The artist's first name is required")]
public string firstname { get; set; }
[Required(ErrorMessage = "The artist's last name is required")]
public string lastname { get; set; }
public Nullable<int> dateOfBirth { get; set; }
public Nullable<int> dateOfDeath { get; set; }
[Required(ErrorMessage = "The artist's speciality is required")]
public string speciality { get; set; }
public string placeOfBirth { get; set; }
}
我的看法则使用性质是这样的:
@model ArtWebShop.Areas.Admin.Models.CreateArtistModel
@Html.EditorFor(model => model.firstname)
@Html.ValidationMessageFor(model => model.firstname)
然后在我的控制器,我保存它是这样的:
[HttpPost]
public ActionResult Create(Artists artist)
{
if (!ModelState.IsValid)
{
return View(CreateArtistWithListOfProductsAndcultures(artist));
}
if (_unitOfWork != null)
{
_unitOfWork.ArtistsRepository.Create(artist);
_unitOfWork.Save();
}
return RedirectToAction("Index", "Overview", new { area = "Admin" });
}
而且工作! 但我不知道为什么...
我想明白为什么这个工程。为什么我的视图模型中的属性自动链接到艺术家模型?
谢谢你的信息。 了解这一点,为什么会使用例如automapper? –
Automapper用于将一个.net类数据映射到另一个.net类数据。为什么要这样?那么使用Automapper的一种场景是将数据对象(关系数据)(如实体框架实体)映射到模型类(DTO)。 – Chandermani
我很困惑,因为我使用Entity框架将数据存储在数据库中,并通过(视图)模型类获取数据。我应该使用automapper吗? 另外我注意到,当我尝试实现同一个更复杂的对象时,从另一个类(例如products - > products_local)继承的模型绑定器似乎无法找到我的属性并将它们正确链接。 –