如何将UIHint属性用于接口的属性类型?

Yar*_*ara 7 c# interface asp.net-mvc-3

我有下一个视图模型:

public class PickUpLocationViewModel 
{
    public DateTime PuDate {get;set}

    public IAddressViewModel {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

取决于IAddressViewModel的实现我想使用适当的UIHint("Airport"),UIHint("Seaport")等.它可能吗?如果有,怎么样?

Ian*_*dge 1

您可以在 TemplateName 的 IAddressViewModel 上创建一个额外的属性,如下所示:

public interface IAddressViewModel
{
    string TemplateName { get; }
}
Run Code Online (Sandbox Code Playgroud)

因此,对于每个实现 IAddressViewModel 的类,您可以定义一个单独的模板名称,例如:

public class SeaportAddressViewModel : IAddressViewModel
{
    public string TemplateName
    {
        get
        {
            return "Seaport";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在您看来,您可以使用 EditorFor 的重载之一,例如:

@Html.EditorFor(m => m.Address, Model.Address.TemplateName)
Run Code Online (Sandbox Code Playgroud)

这应该会导致它使用名为 Seaport.cshtml 的编辑器模板。