我想在剃刀視圖中有一個動態標籤的模型,該模型在運行時設置,但基於使用字符串格式的資源文件中的字符串。如何在運行時自定義顯示和必需屬性在MVC
可以說,我有一個屬性
public class Simple
{
[Display(ResourceType = (typeof(Global)), Name = "UI_Property1")]
[Required(ErrorMessageResourceType = (typeof(Global)), ErrorMessageResourceName = "ERROR_Required")]
[StringLength(40, ErrorMessageResourceType = (typeof(Global)), ErrorMessageResourceName = "ERROR_MaxLength")]
public string Property1{ get; set; }
}
和資源文件的簡單模式有以下字符串
UI_Property1 {0}
ERROR_Required Field {0} is required.
ERROR_MaxLength Maximum length of {0} is {1}
,我願做這樣的事情在Razor視圖
@Html.LabelFor(m => m.Property1, "xyz", new { @class = "control-label col-sm-4" })
並且結果視圖將顯示字段標籤爲'xyz',值' xyz'也將顯示在從服務器模型驗證返回的驗證消息中。
我一直在尋找這樣做的各種方式沒有運氣。我調查覆蓋DisplayAttribute,但這是一個密封的類。
我也看着覆蓋DisplayName屬性,但是這並沒有得到適當的與所需的驗證信息。另外我不知道如何將動態文本插入到我認爲需要在屬性構造函數中完成的屬性中。
我也看過編寫自定義的DataAnnotationsModelMetadataProvider,但無法看到使用它來實現我想要的方式。這可能是由於我缺乏編碼技能。
'xyz'字符串將來自web.config文件中的一個設置,不需要在LabelFor命令中注入,但如果它更有意義,可以注入其他位置。
如果任何人都能給我線索,我該如何實現這一點,這將是偉大的。