使用接口类型为模型的查看和使用真实类型的属性和验证的最佳实践 [英] Best practice for using interface type as model in View and use real type attributes and validations

查看:125
本文介绍了使用接口类型为模型的查看和使用真实类型的属性和验证的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的接口:

public interface IFoo
{
    decimal Amount { get; set; }
}

和我有一些视图模型实现它:

And I have some view models implement it:

public class Foo1 : IFoo
{
    [Display(Name = "Foo1 Amount")]
    [Range(6, 11)]
    public decimal Amount { get; set; }
}

public class Foo2 : IFoo
{       
    [Display(Name = "Foo2 Amount")]
    [Range(1, 5)]
    public decimal Amount { get; set; }
}

我不想为每个新视图 Foo1 foo2的

所以,我创建了一个视图,它具有的IFoo 键入模式。

So, I have created a view which has IFoo type model.

@model IFoo

<div>
    @Html.LabelFor(x => x.Amount)

    @Html.TextBoxFor(x => x.Amount)

    @Html.ValidationMessageFor(x => x.Amount)
</div>

不过,不创建客户端不显眼的属性范围在客户端的属性。

But, it doesn't create client-side unobtrusive attributes like Range attribute in client-side.

如果我为每一个这种类型的一个新的观点,那么everyting都会好的。

If I create a new view for each of this types, then everyting will be ok.

更新:我试图接口更改为抽象类提供的答案,但它并没有帮助也不

Update: I have tried to change interface to abstract class as offered in the answer, but it didn't help neither.

推荐答案

不幸的是,你不能使用接口做到这一点。当您使用HTML辅助生成html,它首先会生成 ModelMetadata 的属性(在强类型HTML辅助的情况下,通过调用

Unfortunately you cannot do this using an interface. When you use a html helper to generate html, it first generates the ModelMetadata for the property (in the case of the strongly typed html helpers, by calling

ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

这生成基于在属性考虑到它的属性的元数据。在 TextBoxFor() GetUnobtrusiveValidationAttributes()的方法的HtmlHelper ,然后调用生成数据-VAL - * 属性

This generates the metadata based on the property taking into account its attributes. In the case of TextBoxFor(), the GetUnobtrusiveValidationAttributes() method of HtmlHelper is then called to generate the data-val-* attributes.

这里的关键是,它的元数据的属性,其获得的元数据,没有任何验证的财产属性。并进一步您的评论的@ Model.GetType()是Foo1或foo2的的,它并不试图获取具体类型的实例,并产生它的元数据。

The key here is that its the metadata for the property, and the property its getting the metadata for does not have any validation attributes. And further to your comment "@Model.GetType() is Foo1 or Foo2", it does not attempt to get an instance of the concrete type and generate its metadata.

除非你创建自己的ModelMetadataProvider并覆盖CreateMetadata()方法,你需要为每个具体类分开的观点。

Unless you were to create your own ModelMetadataProvider and override the CreateMetadata() method, you need to create separate views for each concrete class.

这篇关于使用接口类型为模型的查看和使用真实类型的属性和验证的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆