我对 MVC 还很陌生。我使用接口(interface)
作为我的模型的属性。
我注意到我的数据注释属性
被忽略了。我在提交表单时也遇到错误:
Cannot create an instance of an interface.
我很快就发现我必须使用自定义的 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
接口(interface)和实现:
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
}
最佳答案
您应该尽量避免在 View 模型中使用接口(interface)和抽象类型。因此,在您的情况下,如果采用此 View 模型的 Controller 操作永远不会有除 Place
之外的任何其他 IPlace
实现,那么只需替换接口(interface)即可。
如果由于某种原因您需要它,正如您已经发现的那样,您将必须编写一个自定义模型绑定(bind)器,在其中指定要创建的实现。这是an example .
关于asp.net-mvc - MVC3 模型与 CaSTLe 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10006868/