@ Html.validate方法,它是如何工作的?

时间:2015-06-17 13:25:04

标签: jquery validation asp.net-mvc-4

我已经为表单验证编写了这段代码,它运行良好

  

数据持有人

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace workflow.DataHolders
{
    public class NewCompany
    {
        [Required]
        [StringLength(200, MinimumLength = 3, ErrorMessage="Length Of The Company Name Should  Be More Than Three Letters")]
        public string CompanyName { get; set; }

        [Required]
        [EmailAddress(ErrorMessage="Invalid Email Address")]
        public string Email { get; set; }

        [Required]
        [StringLength(200, MinimumLength = 2, ErrorMessage = "Length Of The Country Name Should  Be More Than Two Letters")]
        public string Country { get; set; }

        public string Description { get; set; }
    }
}
  

查看方

<link href="@Url.Content("~/sharedfiles/css/forms/addnew.css")" rel="stylesheet" type="text/css" />
<div id="Add_container">

   @if (!ViewData.ModelState.IsValid)
   {
       <div id="validationMessage">Please Correct The Errors Below</div> 
   }

    @using (Html.BeginForm("ValidateAndSignUp", "Accounts", FormMethod.Post))
    {
        @Html.AntiForgeryToken()

        @Html.ValidationMessage("CompanyName");
        <span class="field_title">Company Name: </span>
        @Html.TextBox("CompanyName")

        @Html.ValidationMessage("Email");
        <span class="field_title">Email: </span>
        @Html.TextBox("Email")



        @Html.ValidationMessage("Country");
        <span class="field_title">Country Name: </span>
        @Html.TextBox("Country")

        <span class="field_title">About The Company: </span>
        @Html.TextArea("Description")



        <input type="submit" value="Create New Account">


    }
</div>
<div class="get_connected_message">
    <h1>Get Connected with your Customers</h1>
</div>

<div class="get_connected_message">
    <h1>Build your profissional buisness world</h1>
</div>

<div class="clear"></div>
  

ValidateAndSignUp Action

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ValidateAndSignUp(NewCompany newCompany)
{
    if (ModelState.IsValid)
    {

        return RedirectToAction("index", "Home");
    }
    else
    {
        return View("signUp", newCompany);
    }
}

每件事情都很完美且验证正确,但是我尝试了 @ Html.validate 方法,因为我读到它没有其他东西它注册字段进行验证,但这是什么意思?这是否意味着它将其注册为在客户端进行验证,如果是,那该怎么办?

1 个答案:

答案 0 :(得分:0)

@ Html.Validate 注册该属性以进行验证,而无需在验证失败时显示消息。此HTML帮助程序仅在您想要触发验证时使用,但不希望为该控件显示特定错误。在您的情况下,由于您已经在使用ValidationMessage,因此无需使用Validate;因为该属性已经在ValidationMessage帮助程序上注册验证。

此外,如果您启用了不显眼的JavaScript, @ Html.Validate 将返回而不会实际执行任何操作。因为如果你确实有不引人注目的Javascript,那么其他机制将负责注册该属性以进行客户端和服务器验证。