クラスを使用するのと同じ方法で、インターフェースを使用する「EditorTemplate」を使用する必要があります。
2 つの問題があります。
「EditorTemplate」という名前の「DataAnnotation」「DataType」を含めた場合にのみ、「EditorTemplate」を認識します。これはあまり気になりませんが、タイプ (クラス) の名前を持つ「EditorTemplate」がある場合のように、タイプで認識できると便利です。
[DataType ("ICanBeListed")]
私のインターフェイスは、ジェネリックを使用してリストを定義し、プロパティの型を返します。このため、テンプレートの作成方法がわかりません。
2つのクエリがあることは知っていますが、同じ問題を解決します。
アーカイブ:
望ましいビュー モデル:
[DisplayName("Field one")]
public FieldOne MyFieldOne { get; set; }
[DisplayName("Field two")]
public FieldTwo MyFieldTwo { get; set; }
ポイント1の解決策:
[DisplayName("Field one")]
[DataType("ICanBeListed")]
public FieldOne MyFieldOne { get; set; }
[DisplayName("Field two")]
[DataType("ICanBeListed")]
public FieldTwo MyFieldTwo { get; set; }
インターフェース:
public interface ICanBeListed<T, U>
{
U Id { get; set; }
string Description { get; set; }
IList<T> ToList();
}
クラス:
public class FieldOne : ICanBeListed<FieldOne, string>
{
public string Id { get; set; }
public string Descripcion { get; set; }
public IList<FieldOne> List()
{
return new List<FieldOne>
{
new FieldOne{Id = "1", Descripcion = "Description 1"},
new FieldOne{Id = "2", Descripcion = "Description 2"}
};
}
}
public class FieldTwo : ICanBeListed<FieldTwo, int>
{
public int Id { get; set; }
public string Descripcion { get; set; }
public IList<FieldTwo> List()
{
return new List<FieldTwo>
{
new FieldTwo{Id = 1, Descripcion = "Descripcion 1"},
new FieldTwo{Id = 2, Descripcion = "Descripcion 2"}
};
}
}
テンプレート エディタ:
@model Mvc3ConditionalValidation.Models.ICanBeListed<object, object>
@Html.DropDownListFor(model => model.Id, new SelectList(Model.ToList(), "Id", "Description"))
意見:
<div class="editor-field">
@Html.EditorFor(model => model.MyFieldOne)
@Html.ValidationMessageFor(model => model.MyFieldOne)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.MyFieldTwo)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.MyFieldTwo)
@Html.ValidationMessageFor(model => model.MyFieldTwo)
</div>
クラスのインターフェースを変更しようとしています:
モデルを見る:
public class FieldTwo : CanBeListed<FieldTwo, int>
{
public override int Id { get; set; }
public override string Description { get; set; }
public override IList<FieldTwo> ForList()
{
return new List<FieldTwo>
{
new FieldTwo{Id = 1, Description = "Descripcion 1"},
new FieldTwo{Id = 2, Description = "Descripcion 2"}
};
}
}
クラス (インターフェイスの前):
public abstract class CanBeListed<T, U>
{
public virtual U Id { get; set; }
public virtual string Description { get; set; }
public abstract IList<T> ForList();
}
しかし、問題は同じです:
ディクショナリに渡されたモデル アイテムのタイプは 'Mvc3ConditionalValidation.Models.FieldOne' ですが、このディクショナリにはタイプ 'Mvc3ConditionalValidation.Models.CanBeListed`2[System.Object,System.Object]' のモデル アイテムが必要です。
ありがとう