有沒有什麼辦法從View中訪問ViewModel屬性的任何屬性(無論是數據註解屬性,驗證屬性還是自定義屬性)?我希望在屬性具有[Required]屬性的字段旁添加一個必需的指示符。ASP.NET MVC:在視圖上訪問ViewModel屬性
例如,如果我的視圖模型是這樣的:
public class MyViewModel
{
[Required]
public int MyRequiredField { get; set; }
}
我想要做的事在EditorFor模板,像這樣:
<%@ 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>
驗證屬性如我的EditorFor需求上面呢?在那篇博文中,Brad表示影響ModelMetadata的唯一屬性是[HiddenInput],[UIHint],[DataType],[ReadOnly],[DisplayFormat],[ScaffoldColumn]和[DisplayName] – ajbeaven
可通過GetValidators方法。我已經更新了我的答案以反映這一點。但我不確定其他非驗證屬性。 –
獲取屬性信息的另一種方式是通過反射。例如'typeof(YourModel).GetProperty(「PropertyName」)。GetCustomAttributes()',但是你絕對不應該在視圖中這樣做。 –