2011-08-24 61 views
0

我有一個自我驗證模型。提交表單時,錯誤不會顯示在相應文本框下方的視圖中。但是,它只顯示在ValidationSummary中。我希望它顯示在每個文本框下方。謝謝。自我驗證模型不會返回錯誤?

型號:

public class BankAccount : IValidatableObject 
{  
    public string FirstName { get; set; } 
    public string LastName { get; set; } 

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
    { 
    List<ValidationResult> errors = new List<ValidationResult>(); 
    if (string.IsNullOrEmpty(LastName)) 
    { 
     errors.Add(new ValidationResult("Enter valid lastname por favor.")); 
    } 

    if (string.IsNullOrEmpty(FirstName)) 
    { 
     errors.Add(new ValidationResult("Enter valid firstname por favor.")); 
    } 

    return errors; 
    } 
} 

控制器:

public class HomeController : Controller 
    { 
    public ActionResult Index() 
    { 
     BankAccount oBankAccount = new BankAccount(); 
     return View("Home", oBankAccount); 
    } 


    [HttpPost]  
    public ActionResult Index(BankAccount oBankAccount) 
    { 
     return View("Home", oBankAccount); 
    } 
    } 

查看:

@model BankAccountApp.Models.BankAccount 
@{ 
    Layout = null; 
} 
<!DOCTYPE html> 
<html> 
<head> 
    <title>Home</title> 
</head> 
<body> 
    <div>  

    @using (@Html.BeginForm("Index", "Home")) 
    { 
     @Html.ValidationSummary() 

     // FirstName TextBox 
     <span>FirstName: </span> 
     @Html.TextBoxFor(model => model.FirstName) 
     @Html.ValidationMessageFor(model => model.FirstName) 

     <br /> 

     // LastName TextBox 
     <span>LastName: </span> 
     @Html.TextBoxFor(model => model.LastName) 
     @Html.ValidationMessageFor(model => model.LastName, null, new { @class = "formErrors" })  

     <input type="submit" value="submit me" /> 
    } 

    </div> 
</body> 
</html> 
+0

當你標記你的'用'LastName'屬性會發生什麼[必需(的ErrorMessage = 「測試」)]'屬性? – Tejs

+0

當我按照你說的添加必要的屬性時,如果沒有填充任何內容,它會在旁邊顯示「測試」。如果填充了內容,則不顯示任何內容。 – SaltProgrammer

回答

3

改變你的方法如下

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
    { 
    if (string.IsNullOrEmpty(LastName)) 
    { 
     yield return new ValidationResult("Enter valid lastname por favor", new[] { "LastName" }); 
    } 

    if (string.IsNullOrEmpty(FirstName)) 
    { 
     yield return new ValidationResult("Enter valid firstname por favor.", new[] { "FirstName" }); 
    } 
    } 
+0

這很好。謝謝一堆!你能解釋我爲什麼沒有工作,這個工作嗎? – SaltProgrammer

+2

如果您沒有將字段名稱作爲第二個參數提供給ValidationResult構造函數,那麼運行時將結果與模型相關聯,而不是模型上的特定屬性。 Html.ValidationMessageFor正在查找與表達式中的屬性相關聯的結果,但未找到與模型相關的結果。 – OdeToCode

+1

@salt程序員傳奇人物Scott Allen(OdeToCode)在上面的評論中回答了你的問題。 –

0

這聽起來像你用於製作模型驗證已過時的方法。我會建議轉到DataAnnotations方法來驗證模型。這似乎工作。

+0

是什麼讓你說它已經過時了?它已被棄用?謝謝。 – SaltProgrammer