不幸的是,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
如果你喜歡這個主意,請投上一票的用戶語音。希望這可以幫助。
您使用的web表單或MVC? – 2013-02-19 02:40:59
是的,我發佈了一個答案,認爲它是MVC,但後來不確定,我認爲他的意思是WebForms。 – 2013-02-19 02:48:26
我忘了提及,是的,我們正在使用webforms。 – user2085436 2013-02-20 03:02:20