2

我很新MVC。我正在使用interface作为我的模型的属性。MVC3模型绑定与城堡

我注意到我的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 
} 
+1

在这里使用界面有什么意义?摆脱它,并使用类“地方” – 2012-04-04 11:18:56

回答

2

您应该尽量避免在视图模型中使用接口和抽象类型。所以在你的情况下,如果采取这种视图模型的控制器动作永远不可能有比Place更具有IPlace的任何其他实现,那么简单地替换该接口。

如果由于某种原因需要它,就像您已经发现的那样,您将不得不编写一个自定义模型联编程序,在其中指定要创建的实现。这里是an example