2013-12-11 30 views
0

我有以下的ASP.NET MVC過濾屬性:讀值和篩選器屬性添加錯誤

public void OnActionExecuting(ActionExecutingContext context) { 
    ControllerBase controller = context.Controller;  
} 

並在視圖上我有

@Html.TextBox("Captha"); 

一種形式,我的模型是:

public class SignUpModel { 
    public String Email { get; set; } 
    public String Password { get; set; } 
    public String Captcha { get; set; } 
} 

我怎樣才能在我的過濾器屬性,請執行下列操作:

  1. 獲取插入到文本框中的值;

  2. 如果沒有值或特定條件爲false,那麼向模型狀態添加錯誤?

  3. 我需要我的模型中的captcha屬性嗎?

謝謝你, 米格爾

+0

你想在你的TextBox中插入什麼值?你的ActionFilter應該做什麼? – ataravati

+0

基本上,我需要閱讀插入到文本框中的文本,並將其與會話值進行比較。如果它們不同,那麼我想向模型狀態添加一個錯誤,以便在驗證助手的視圖中顯示 –

+0

您可以發佈您的模型嗎? – ataravati

回答

1

你並不需要一個ActionFilter做到這一點。在模型中使用CompareAttribute來驗證Captcha屬性。另一個屬性添加到您的模型,並將其命名爲SessionValue,然後用CompareAttributeCaptcha屬性中輸入的值與SessionValue性能比較:

public class SignUpModel { 
    public string Email { get; set; } 
    public string Password { get; set; } 
    [Compare("SessionValue")] 
    public string Captcha { get; set; } 
    public string SessionValue { get; set; } 
} 

然後,在你的控制器動作設置SessionValue屬性的值存儲在會話中的值:

var model = new SignUpModel(); 
model.SessionValue = Session["MyValue"]; 
return View(model); 

而且,在你看來,你必須:

@Html.HiddenFor(model => model.SessionValue) 
@Html.TextBoxFor(model => model.Captcha) 
@Html.ValidationMessageFor(model => model.Captcha) 

UPDATE:

如果你不希望有SessionValue在您查看隱藏的輸入,你可以創建一個自定義的驗證屬性是這樣的:

using System.ComponentModel.DataAnnotations; 
using System.Web; 

public class MyCustomValidationAttribute : ValidationAttribute 
{ 
    public override bool IsValid(object value) 
    { 
     if (value == null) 
      return true; 

     string compareValue = HttpContext.Current.Session["MyValue"]; 

     return (string)value.Equals(compareValue); 
    } 
} 

而且,使用它你這樣的模型:

public class SignUpModel { 
    public string Email { get; set; } 
    public string Password { get; set; } 
    [Required] 
    [MyCustomValidation] 
    public string Captcha { get; set; } 
} 
+0

隨着你的方法,我不需要將SessionValue作爲我的視圖中的隱藏輸入?這是不安全的... –

+0

你說得對。看到我更新的答案。 – ataravati