通过DataAnnotations进行ASP.Net MVC验证

时间:2010-09-04 10:10:41

标签: asp.net-mvc validation data-annotations

我关注了scottgu的博客here,并尝试进行数据验证。成功了。但是我看到的是,如果我的字段是必填字段,一旦我从文本框中松开焦点,我就会收到错误。我希望只有在我点击提交时才会进行验证。

1 个答案:

答案 0 :(得分:0)

该文章是关于使用客户端验证,因此您可以在客户端验证您的表单。因此,当你失去焦点时,表格会被jquery验证!

一种方法是使用服务器端验证..在这种情况下,您将刷新页面。

更新:

以下是示例代码 型号:

public class GuestForm
    {
        [Required(ErrorMessage="Please enter your name")]
        public string Name { get; set; }

        [Required(ErrorMessage="Please enter your phone number")]
        public string Phone { get; set; }

        [Required(ErrorMessage="Please enter your email address")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Please enter your choice")]
        public bool? YesNo { get; set; }
    }

形式:

<div>
<% using(Html.BeginForm()) { %>
    <%= Html.ValidationSummary() %>
    Name: <%= Html.TextBoxFor(x => x.Name) %><br/>
    Email: <%= Html.TextBoxFor(x => x.Email) %><br/>
    Phone: <%= Html.TextBoxFor(x => x.Phone) %><br/>
    Will you attend?
    <%= Html.DropDownListFor(x => x.YesNo, new[] {
      new SelectListItem { Text = "Yes",Value = bool.TrueString },
      new SelectListItem { Text = "No",Value = bool.FalseString }
      }, "Choose...") %><br/>
   <input type="submit" value="Register!" />
<% } %>
</div>

控制器:

        [HttpGet]
        public ViewResult RegisterForm()
        {
            return View();
        }

        [HttpPost]
        public ViewResult RegisterForm(GuestForm form)
        {
            if (ModelState.IsValid)
                return View("Thanks", form);
            else
                return View();
        }

当用户点击提交时,此代码将看到您的表单在服务器端验证。 它将以列表的形式在表单顶部显示错误消息。

我希望这会对你有所帮助。

相关问题