我在尝试使用以下型号保存约会时遇到问题。
实体模型:
public class Appointment
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
public DateTime StartDateTime { get; set; }
public DateTime FinishDateTime { get; set; }
[StringLength(1024)]
[DataType(DataType.MultilineText)]
public string Outcome { get; set; }
public virtual AppointmentType AppointmentType { get; set; }
public int CustomerId { get; set; }
}
public class AppointmentType
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
[StringLength(100)]
public string Type { get; set; }
}
我正在使用DropDown List(Selectlist)从ViewModel填充视图中的AppointmentType。
public class BookAppointmentViewModel
{
public SelectList AppTypes { get; private set; }
public Appointment Appointment { get; private set; }
public BookAppointmentViewModel(Appointment appointment, IEnumerable<AppointmentType> appTypes)
{
Appointment = appointment;
AppTypes = new SelectList(appTypes, "Type", "Type");
}
}
然而,当我点击保存时,我收到验证错误消息The value 'General Appointment' is invalid
- 其中一般约会可以是任何选定的AppointmentType。
如何在约会中保存 AppointmentType - 而不是AppointmentType.Type?
答案 0 :(得分:1)
DropDownList只能在提交表单时发送简单的标量值。因此,您希望从客户端获得的是此下拉列表绑定的ID:
@Html.DropDownListFor(x => x.Appointment.Id, Model.AppTypes)
在服务器上,您可以使用此Id
来检索相应的Type
属性,如果您需要存储此信息的位置(我想是一个数据库)。