1

我在尝试使用以下模型保存约会时遇到问题。

实体模型:

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

我正在使用下拉列表 (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- 一般约会可以是任何选定的约会类型。如何在 Appointment 中保存AppointmentType - 而不是 AppointmentType.Type?

4

1 回答 1

1

DropDownList 只能在提交表单时发送简单的标量值。因此,您希望从客户端获得的只是此下拉列表绑定到的 ID:

@Html.DropDownListFor(x => x.Appointment.Id, Model.AppTypes)

在服务器上,如果您需要从存储此信息的任何位置(我想是数据库),您可以使用它Id来检索相应的属性。Type

于 2013-05-20T15:13:48.373 回答