ASP.NET MVC:访问视图模型视图上的属性 [英] ASP.NET MVC: Accessing ViewModel Attributes on the view
问题描述
有没有办法从视图访问视图模型的属性(可以是数据标注属性,属性验证或自定义属性)的属性?其中一件事我想有点所需指标添加到旁边的田酒店有[必需]属性。
例如,如果我的视图模型是这样的:
公共类MyViewModel
{
[需要]
公众诠释MyRequiredField {搞定;组; }
}
我希望做的EditorFor模板像这样:
<%@控制语言=C#继承=System.Web.Mvc.ViewUserControl<&诠释GT; %GT;< DIV CLASS =标签容器>
&所述;%:Html.Label()%> <%,如果(PROPERTY_HAS_REQUIRED_ATTRIBUTE){%GT;
<跨度类=必需> * LT; / SPAN>
<%}%GT;
< / DIV>
< DIV CLASS =字段容器>
&所述;%:Html.TextBox()%>
&所述;%:Html.ValidationMessage()%>
< / DIV>
您正在寻找的信息是 ViewData.ModelMetadata code>。布拉德·威尔逊的博客帖子一系列模板应该解释这一切,特别是在的 ModelMetadata A>。
至于其他ValidationAttributes去,你可以通过的 ModelMetadata.GetValidators()
方法。
ModelMetadata.IsRequired
会告诉你,如果一个复杂类型(或价值型包裹在可空< T>
)由 RequiredAttribute标签
必需的,但它会给你误报为不可为空值类型(因为它们隐含需要)。您可以解决这跟以下内容:
布尔isReallyRequired = metadata.IsRequired
&功放;&安培; (!metadata.ModelType.IsValueType || metadata.IsNullableValueType);
请注意:您需要使用 metadata.ModelType.IsValueType
而不是 model.IsComplexType
,因为<$! C $ C> ModelMetadata.IsComplexType 返回MVC虚假不认为是一个复杂的类型,包括字符串。
Is there any way to access any attributes (be it data annotation attributes, validation attributes or custom attributes) on ViewModel properties from the view? One of the things I would like to add a little required indicator next to fields whose property has a [Required] attribute.
For example if my ViewModel looked like this:
public class MyViewModel
{
[Required]
public int MyRequiredField { get; set; }
}
I would want to do something in the EditorFor template like so:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<int?>" %>
<div class="label-container">
<%: Html.Label("") %>
<% if (PROPERTY_HAS_REQUIRED_ATTRIBUTE) { %>
<span class="required">*</span>
<% } %>
</div>
<div class="field-container">
<%: Html.TextBox("") %>
<%: Html.ValidationMessage("") %>
</div>
The information you're looking for is in ViewData.ModelMetadata
. Brad Wilson's blog post series on Templates should explain it all, especially the post on ModelMetadata.
As far as the other ValidationAttributes go, you can access them via the ModelMetadata.GetValidators()
method.
ModelMetadata.IsRequired
will tell you if a complex type (or value type wrapped in Nullable<T>
) is required by a RequiredAttribute
, but it will give you false positives for value types that are not nullable (because they are implicitly required). You can work around this with the following:
bool isReallyRequired = metadata.IsRequired
&& (!metadata.ModelType.IsValueType || metadata.IsNullableValueType);
Note: You need to use !metadata.ModelType.IsValueType
instead of model.IsComplexType
, because ModelMetadata.IsComplexType
returns false for MVC does not consider to be a complex type, which includes strings.
这篇关于ASP.NET MVC:访问视图模型视图上的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!