不幸的是,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