2013-02-19 94 views
5

我GOOGLE了這個廣泛,找不到答案,所以我張貼這裏希望尋求幫助。在asp.net 4.5驗證錯誤

我們有一個asp.net 4.5項目,在數據庫對象類中指定了驗證。例如:

[Required(ErrorMessage = "Name is a required field.")] 
public string Name { get; set; } 

有沒有辦法在所有我們能有此錯誤消息顯示字段旁邊表單頁面上?驗證總結顯示得很好,但我們真的希望在沒有使用傳統的,代碼沉重的asp.net驗證器(RequiredFieldValidator和其他)的情況下讓它們顯示在它們各自的字段旁邊。

感謝您的幫助。

編輯:我們正在使用的WebForms,而不是MVC

+2

您使用的web表單或MVC? – 2013-02-19 02:40:59

+0

是的,我發佈了一個答案,認爲它是MVC,但後來不確定,我認爲他的意思是WebForms。 – 2013-02-19 02:48:26

+0

我忘了提及,是的,我們正在使用webforms。 – user2085436 2013-02-20 03:02:20

回答

1

不幸的是,Web窗體模型綁定驗證框架是不是爲MVC全面而。首先,數據註釋的客戶端驗證不是內置的。我知道顯示數據註釋錯誤的唯一方法是通過ValidationSummary控件,該控件具有ShowModelStateErrors屬性(默認爲true)。這裏是一個超級簡單的例子:

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
     <asp:FormView ID="FormView" runat="server" RenderOuterTable="false" ItemType="Person" 
      DefaultMode="Insert" InsertMethod="FormView_InsertItem"> 
      <InsertItemTemplate> 
       <asp:ValidationSummary ID="ValSummary" runat="server" ValidationGroup="FormGroup" 
        HeaderText="The following problems occured when submitting the form:" /> 
       <table> 
        <tr> 
         <td> 
          <asp:Label ID="NameLabel" runat="server" AssociatedControlID="NameField">Name</asp:Label> 
         </td> 
         <td> 
          <asp:TextBox ID="NameField" runat="server" Text='<%# BindItem.Name %>' ValidationGroup="FormGroup" /> 
         </td> 
        </tr> 
       </table> 
       <asp:Button ID="SaveButton" runat="server" CommandName="Insert" Text="Save" ValidationGroup="FormGroup" /> 
      </InsertItemTemplate> 
     </asp:FormView> 
    </form> 
</body> 
</html> 

代碼背後:

public partial class create_person : System.Web.UI.Page 
{ 
    public void FormView_InsertItem() 
    { 
     var p = new Person(); 
     TryUpdateModel(p); 
     if (ModelState.IsValid) 
     { 
      Response.Write("Name: " + p.Name + "<hr />"); 
     } 
    } 
} 

類別:

using System.ComponentModel.DataAnnotations; 

public class Person 
{ 
    [Required, StringLength(50)] 
    public string Name { get; set; } 
} 

因爲沒有客戶端/數據註釋驗證的javascript支持,生成模型狀態錯誤的唯一方法是在回發之後。如果您需要在控件旁邊進行內聯驗證,則仍然需要使用標準驗證控件。

我已經張貼在用戶語音的功能要求,要求他們考慮改進數據註解集成: http://aspnet.uservoice.com/forums/41202-asp-net-web-forms/suggestions/3534773-include-client-side-validation-when-using-data-ann

如果你喜歡這個主意,請投上一票的用戶語音。希望這可以幫助。

2

您可以使用ModelErrorMessage控件。例如,讓我們假裝你有一個名字屬性的模型。 您將添加這樣的事情:

<asp:ModelErrorMessage ID="FirstNameErrorMessage" ModelStateKey="FirstName" runat="server" />