获取模型属性之一的 ModelMetadata
我正在读布拉德·威尔逊的一篇文章:
ASP.NET MVC 2 模板,第 2 部分:模型元数据
http:// /bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-2-modelmetadata.html
让我们假设在我的 ASP.NET MVC 3 应用程序上,我有以下模型:
public class Contact {
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
这是我的观点:
@model MyApp.Models.Contact
<h2>Contact</h2>
@Html.EditorForModel()
并且我里面有一个 Contact.cshtml
文件~/Views/Shared/EditorTemplates/
路径。
我的问题是如何访问每个模型属性的 ModelMetadata
。例如,如下所示:
Contact.cshtml
@model MyApp.Models.Contact
<input type="text" placeholder="@Model.FirstName.GetItsMetaData().Watermark"
value="@Model.FirstName" />
注意: GetItsMetaData 方法完全是我编造的。我只是想访问该属性的 MedelMetadata。没有 就这样。
编辑
我发现了另一个类似的问题:
ASP.NET MVC 中的 editortemplate 中的复杂类型的 ModelMetadata
答案是这样的:
@{
var metadata = ModelMetadata
.FromLambdaExpression<TestThing, string>(x => x.Test2, ViewData);
var watermak = metadata.Watermark;
}
但是对模型的每个属性执行此操作非常冗长,不是吗?
I was reading one of Brad Wilson's articles:
ASP.NET MVC 2 Templates, Part 2: ModelMetadata
http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-2-modelmetadata.html
Let's assume that on my ASP.NET MVC 3 App, I have the following model:
public class Contact {
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
And here is my view:
@model MyApp.Models.Contact
<h2>Contact</h2>
@Html.EditorForModel()
and I have a Contact.cshtml
file inside ~/Views/Shared/EditorTemplates/
path.
My question is how I can reach out to ModelMetadata
of each model property. For example, like following:
Contact.cshtml
@model MyApp.Models.Contact
<input type="text" placeholder="@Model.FirstName.GetItsMetaData().Watermark"
value="@Model.FirstName" />
NOTE: GetItsMetaData method is something which I totally made up. I am just trying to get to MedelMetadata of the property. Doesn't have
to be that way.
EDIT
I found another similar question:
ModelMetadata for complex type in editortemplate in asp.net mvc
and the answer is this:
@{
var metadata = ModelMetadata
.FromLambdaExpression<TestThing, string>(x => x.Test2, ViewData);
var watermak = metadata.Watermark;
}
But it is quite verbose to do this for every single property of my model, isn't it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建一个用于此目的的 HtmlHelper 就不那么冗长了。该帮助器将如下所示:
您将在示例中按如下方式使用它:
It is less verbose to create an HtmlHelper to use for this purpose. The helper would look like this:
You would use it as follows in your example: