2012-02-28 25 views
3

我已經建立一個搜索字符串searchmodel並用minlength裝飾它。在我的視圖中,我想顯示搜索字符串的必要條件,但是如何才能找到裝飾?如何在視圖中顯示模型裝飾?

型號:

public class SearchModel 
{ 
    [StringLength(50,MinimumLength = 4)] 
    public string Searchname { get; set; } 
} 

剃刀:

@model Project.Models.SearchModel 

<p> 
    The search value has to be a min length of: ... 
</p> 
+0

常量?但我同意一個獲取屬性值的函數會更好。我認爲這可以通過反思。 – Marthijn 2012-02-28 11:02:04

回答

2

你可以這樣做:

@(typeof(SearchModel).GetProperty("Searchname").GetCustomAttributes(true) 
    .OfType<StringLengthAttribute>().First().MinimumLength) 

雖然對MVC純度的緣故,你應該避免將這種邏輯到視圖代碼。或者:

  • 讓您的控制器獲得此信息,並把它放到模型本身作爲一個單獨的屬性,或
  • 使用自定義ModelMetadataProvider,使通過模型元數據提供的信息。
+0

我喜歡你的簡單解決方案:-),但有一個問題**「方法沒有重載'GetCustomAttributes'需要0個參數」**(也許還需要添加命名空間?) – Zoli 2012-02-28 16:00:49

+2

這很好:'typeof(NAMESPACE。 SearchModel).GetProperty( 「Searchname」)。GetCustomAttributes(真).OfType ()。首先()。MinimumLength' – Zoli 2012-02-28 16:08:03

1

你可以得到驗證屬性在客戶端此值。

$('#Searchname').attr('data-val-length-min') 

或者您需要在服務器端使用剃鬚刀?

@{ 
    var attr = typeof(NAMESPACE.SearchModel).GetProperty("Searchname").GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.StringLengthAttribute), true)[0]; 
    var min = attr.GetType().GetProperty("MinimumLength").GetValue(attr, null); 
} 
. 
. 
. 
<p>The search value has to be a min length of: @min</p> 
+0

我也考慮過了,如果沒有更好的方法,我會這樣做:-) – jwillmer 2012-02-28 14:59:58

+1

也增加了一個剃鬚刀/ C#解決方案。請享用! – Zoli 2012-02-28 15:31:01

相關問題