我試圖訪問模型的元數據屬性來創建一個幫助器,以便基於DataAnnotations自動添加HtmlAttributes。ModelMetadata附加屬性始終爲空
問題是,屬性總是空的。
我有2個基本類,試圖在一個空的項目:
namespace MegaInterestingProject
{
public class HomeController : Controller
{
public string Index()
{
var model = ModelMetadata.FromLambdaExpression<HomeModel, string>(x => x.User, new ViewDataDictionary<HomeModel>());
return model.Description;
}
}
public class HomeModel
{
[Required]
[MaxLength(13)]
[MinLength(11)]
[DisplayName("displayname")]
[Description("description")]
public string User { get; set; }
}
}
這裏model.Description永遠是空的,AdditionalValues字典總是空的。
這裏可能缺少一些東西嗎?
這裏是一個參考項目,我在GitHub上說:https://github.com/erickgirard/TestHtmlAttributesHelper
你爲什麼要聲明一個變量propertyName的?你似乎並沒有真正使用它呢?再說,我已經走了泛型方法和已經完成一個使用這種結構的擴展方法,但是仍然爲空的屬性 – Erick
確實,這是我從我的一個實際功能中挑選出來的一些代碼,我修改了這些代碼進行了說明,但是我將它留下來說明如何知道哪些屬性在你實際使用的模型中,這是你可以用來擴展@Htmlhelper的html helper函數的代碼,但重點是:你試圖從模型級讀取元數據,而實際的屬性值駐留在在model.property級別。 – souplex
我做了一個代碼的複製和粘貼。仍然是空的。我編輯了我的第一篇文章,在github上進行了一個測試項目 – Erick