C# 跨不同类型安全地重用编辑器模板

C# 跨不同类型安全地重用编辑器模板,c#,asp.net-mvc,mvc-editor-templates,C#,Asp.net Mvc,Mvc Editor Templates,假设Decimal的以下部分视图位于~/Views/Shared/EditorTemplates/Decimal.cshtml: 我还想将此模板用于Int32类型的属性。因此,我在~/Views/Shared/EditorTemplates/Int32.cshtml创建了以下内容: 有没有更好的方法重用编辑器模板?这种模式是否有我可能忽略的后果 编辑:添加了从int到decimal的显式强制转换?您可以将一个editor模板定义为一个整体。为两种数据类型定义一次。 例如,您可以使用以下代码示例:

假设Decimal的以下部分视图位于~/Views/Shared/EditorTemplates/Decimal.cshtml:

我还想将此模板用于Int32类型的属性。因此,我在~/Views/Shared/EditorTemplates/Int32.cshtml创建了以下内容:

有没有更好的方法重用编辑器模板?这种模式是否有我可能忽略的后果


编辑:添加了从int到decimal的显式强制转换?

您可以将一个editor模板定义为一个整体。为两种数据类型定义一次。 例如,您可以使用以下代码示例:

EditorTemplate的定义:

~/Views/Shared/EditorTemplates/Number.cshtml
视图中辅助对象的UAMessage:

@Html.EditorFor(model => model.SomeValue)
ViewModel类中的定义为

[UIHint("Number")]
public int SomeValue { get; set; }


有没有一种方法可以做到这一点,而不必重复每个属性的号码或每次呼叫EditorFor?是的,这不是必要的,我更新了我的答案,试试看。
@Html.EditorFor(model => model.SomeValue)
[UIHint("Number")]
public int SomeValue { get; set; }
[UIHint("Number")]
public decimal SomeValue { get; set; }