@Html.validate 方法,它是如何工作的?
Posted
技术标签:
【中文标题】@Html.validate 方法,它是如何工作的?【英文标题】:@Html.validate method, how does it work? 【发布时间】:2015-09-02 18:31:22 【问题描述】:我已经为表单验证编写了这段代码,它运行良好
数据持有者
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 操作
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ValidateAndSignUp(NewCompany newCompany)
if (ModelState.IsValid)
return RedirectToAction("index", "Home");
else
return View("signUp", newCompany);
每件事都完美运行并且可以正确验证,但是我尝试了 @Html.validate 方法,因为我读到它没有做任何其他事情,它会注册字段以进行验证,但这意味着什么?这是否意味着它注册它以在客户端进行验证,如果是,如何做到这一点?
【问题讨论】:
如果您使用@Html.ValidationMessage()
(或ValidationMessageFor()
),则没有理由使用@Html.Validate()
(或ValidateFor()
)
@StephenMuecke 是的,我知道,但我想了解它是如何工作的?
我认为它强制验证没有@Html.ValidationMessage() 的给定字段,您可以自己显示消息...
【参考方案1】:
@Html.Validate 注册属性以进行验证,而无需在验证失败时显示消息。此 HTML 帮助程序仅在您想要触发验证但不想显示该控件的特定错误时使用。在您的情况下,由于您已经在使用 ValidationMessage,因此无需使用 Validate;因为该属性已在 ValidationMessage 帮助器上注册以进行验证。
此外,如果您启用了不显眼的 javascript,@Html.Validate 将直接返回而无需实际执行任何操作。因为如果您确实有不显眼的 Javascript,那么其他机制将负责注册属性以进行客户端和服务器验证。
【讨论】:
以上是关于@Html.validate 方法,它是如何工作的?的主要内容,如果未能解决你的问题,请参考以下文章
这种排序方法的名称是啥,它是如何工作的,它与 Arrays.sort() 相比如何?
使用 DialogFragment 从布局 xml 调用方法。它是如何工作的?