【问题标题】:Using ViewModel with foreign key使用带有外键的 ViewModel
【发布时间】:2015-02-15 15:19:45
【问题描述】:

我有一个简单的场景,但不知道如何设置 ViewModel。我有一个CustomerController.csCreate.cshtmlEdit.cshtml。在这些视图中,我有一些字段可以输入基本的客户信息,例如姓名、电话、传真、电子邮件。

我的Customer 表中有一个名为AddressId 的外键。 Address 表由 AddressId, Address1, Address2, City, State, Zip 之类的列组成。

我正在使用实体框架,所以我可以通过 Customer.Address 简单地获取客户的地址

我的表单包含客户和地址字段,这是我的困惑所在。我是否需要所有地址字段,我是否至少需要 AddressId 这是外键,我不需要 @987654330 @,但只是Address等。

这是我目前在CustomerInfoViewModel 中的内容:

public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
public int AddressId { get; set; }
//Address fields
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }

[Display(Name = "State")]
public int StateId { get; set; }

[Display(Name = "Zip Code")]
public string ZipCode { get; set; }

[Display(Name = "Country")]
public int CountryId { get; set; }

我在页面上有一个StateCountry 下拉菜单,所以我想我只需要StateCountry 的ID。所以我很困惑我是否执行上述所有操作,或者添加所有 Address 字段,只需添加:

public Address Address { get; set; }

【问题讨论】:

  • 当前CustomerInfoViewModel 的一个优点是您可以灵活地添加特定于视图的验证属性(例如,您可能将[RegularExpression] 属性应用于ZipCode)。视图模型还应该包括用于 StateCountry 的 SelectList 的属性

标签: c# asp.net-mvc razor asp.net-mvc-5 viewmodel


【解决方案1】:

你也应该能够做到。最大的决定因素是您是否要拉入并将属性绑定到视图模型或实体模型。所以你是否决定:

[HttpPost]
public ActionResult Edit(CustomerInfoViewModel vm)

或者

[HttpPost]
public ActionResult Edit(Customer model)

更多的是关于代码风格。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 2020-12-18
    • 2021-04-23
    • 2015-07-06
    • 2013-06-11
    • 1970-01-01
    相关资源
    最近更新 更多