问题描述
我非常喜欢使用数据注释的 asp.net 4.5 webforms 模型绑定.
I'm a huge fan of asp.net 4.5 webforms model binding using data annotations.
ascx:
<asp:FormView ItemType="Contact" runat="server" DefaultMode="Edit"
SelectMethod="GetContact" UpdateMethod="SaveContact">
<EditItemTemplate>
<asp:ValidationSummary runat="server" ID="valSum" />
Firstname: <asp:TextBox runat="server" ID="txtFirstname" Text='<%#: BindItem.Firstname %>' />
Lastname: <asp:TextBox runat="server" ID="txtLastname" Text='<%#: BindItem.Lastname %>' />
Email: <asp:TextBox runat="server" ID="txtEmail" Text='<%#: BindItem.Email %>' />
<asp:Button ID="Button1" runat="server" Text="Save" CommandName="Update" />
</EditItemTemplate>
</asp:FormView>
.cs:
public void SaveContact(Contact viewModel)
{
if (!Page.ModelState.IsValid)
{
return;
}
}
public Contact GetContact()
{
return new Contact();
}
型号:
public class Contact
{
[Required]
[StringLength(10, ErrorMessage="{1} tis te lang")]
public string Firstname { get; set; }
[Required]
[StringLength(10)]
public string Lastname { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
}
问题:
是否像 MVC 一样在 webforms 中支持开箱即用的客户端验证?或者我们应该依赖第三方库(DAValidation).是否可以将 Html.EnableClientValidation() 的优点移植到网络表单中?
Is client side validation supported out-of-the-box in webforms like in MVC? Or should we rely on third party libraries (DAValidation). Is it possible to port the goodness of Html.EnableClientValidation() to webforms ?
问候,
巴特
推荐答案
正如我们在 ASP.NET WebForms 项目中发现的那样,对于客户端验证,模型的验证属性没有整体有用的重用.
As we have found in our ASP.NET WebForms projects, there is no overall useful reuse of the Model's validation attributes for client side validation.
例如,具有姓名、电子邮件、生日等各种属性的联系人数据模型并不总是以相同的方式使用.有时它可能有一些必填字段,有时没有,甚至所需的输入数据在应用程序的不同点也可能不同.
For example, a contact data model, with various properties like name, email, birthday etc... is not always used the same way. Sometimes it may have some mandatory fields, sometimes not, and even the required input data may differ at various points in the application.
因此,在我们的项目中,我们同时使用客户端验证实现和模型属性.
Thus, in our projects, we use both a client side validation implementation, and the model attributes.
我们应用的总体思路是:
The general idea we apply is:
- 在客户端,我们希望尽可能具体,以避免不必要的回传,并为用户提供即时、具体的响应.
- 在服务器端,我们应用模型属性以及更多的数据库和面向业务的验证规则,并没有那么具体地失败.此外,如果需要,当某些字段相互依赖时,会进行一些属性间"验证.
对于客户端,我们选择了 jQuery 验证插件(http://jqueryvalidation.org/).
For the client side, we have chosen the jQuery Validate Plugin (http://jqueryvalidation.org/).
我们甚至构建了自己的一组控件(源自内置的 WebControl),它们呈现各种(甚至一些自定义)数据规则.
We even have built our own set of controls (that derive from the built-in WebControls), which render various (and even some custom) data rules.
这篇关于asp.net 4.5 webforms 模型绑定:支持客户端验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!