【发布时间】:2017-06-30 22:52:57
【问题描述】:
我对 MVC 很陌生。我正在使用 interface 作为模型的属性。
我注意到我的Data Annotation Attributes 被忽略了。我在提交表单时也遇到了错误:
无法创建接口的实例。
我很快发现我必须使用自定义的ModelBinder
我很难确定在 ModelBinder 的 CreateModel 方法中需要做什么
我有以下RegistrationModel:
public class RegistrationModel
{
#region Properties (8)
public string Email { get; set; }
public string FirstName { get; set; }
public Gender Gender { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public string PasswordConfirmation { get; set; }
public IPlace Place { get; set; }
public string Username { get; set; }
#endregion Properties
}
这是IPlace的接口和实现:
public interface IPlace
{
#region Data Members (7)
string City { get; set; }
string Country { get; set; }
string ExternalId { get; set; }
Guid Id { get; set; }
string Name { get; set; }
string Neighborhood { get; set; }
string State { get; set; }
#endregion Data Members
}
public class Place : IPlace
{
#region Implementation of IPlace
public Guid Id { get; set; }
[StringLength(100, ErrorMessage = "City is too long.")]
public string City { get; set; }
[StringLength(100, ErrorMessage = "Country is too long.")]
public string Country { get; set; }
[StringLength(255, ErrorMessage = "External ID is too long.")]
public string ExternalId { get; set; }
[Required(ErrorMessage = "A name is required.")]
[StringLength(450, ErrorMessage = "Name is too long.")]
[DisplayName("Location")]
public string Name { get; set; }
[StringLength(100, ErrorMessage = "Neighborhood is too long.")]
public string Neighborhood { get; set; }
[StringLength(100, ErrorMessage = "State is too long.")]
public string State { get; set; }
#endregion
}
【问题讨论】:
-
这里使用接口有什么意义?摆脱它并使用“Place”类
标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-2 castle-windsor custom-model-binder