你並不需要一個ActionFilter做到這一點。在模型中使用CompareAttribute
來驗證Captcha屬性。另一個屬性添加到您的模型,並將其命名爲SessionValue
,然後用CompareAttribute
爲Captcha
屬性中輸入的值與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; }
}
你想在你的TextBox中插入什麼值?你的ActionFilter應該做什麼? – ataravati
基本上,我需要閱讀插入到文本框中的文本,並將其與會話值進行比較。如果它們不同,那麼我想向模型狀態添加一個錯誤,以便在驗證助手的視圖中顯示 –
您可以發佈您的模型嗎? – ataravati