如何Page.IsValid工作? [英] How does Page.IsValid work?

查看:392
本文介绍了如何Page.IsValid工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下code以的RequiredFieldValidator 。在 EnableClientScript 属性设置为验证控件假。我也有禁用脚本的浏览器。

我不是在code。使用 Page.IsValid 后面。然而,当我在文本框中没有任何值提交我将获得错误信息

从@Dai的意见,我才知道,这可能是一个问题,如果在的Page_Load 任何code,它是在<$执行C $ C>回发。会有抛出任何验证错误。

(但是,对于按钮单击处理程序,没有必要检查 Page.IsValid

 如果(Page.IsPostBack)
{
    字符串值= txtEmpName.Text;
    txtEmpName.Text =值+追加;
}


  1. 为什么没有在服务器端验证发生之前的Page_Load

  2. 为什么它工作得很好,当我使用 Page.IsValid

  3. 你能提供一个解释这一篇文章的内容? (不是,说 - 总是用 Page.IsValid ;但有些事,说什么都是强制性的方案中使用 Page.IsValid

更新1

请参照<一个href=\"http://blogs.microsoft.co.il/blogs/linqed/archive/2009/09/01/asp-net-validators-common-misconception.aspx\"相对=nofollow> ASP.NET验证器常见的误解


  

Page.IsValid 仅在运行后,可以访问它隐含某处后<调用 Page.Validate()方法code>的Page_Load 。如果你把所有你的逻辑在Page_Load事件处理程序(这是高度气馁!),调用 Page.Validate()检查前的 Page.IsValid


注意的:这是建议的不保留的所有在的Page_Load 逻辑。如果事情是发生在按钮的单击事件,将其移动到按钮单击事件处理程序。如果事情是在下拉事件的发生,移动到下拉列表中选择项目更改事件处理程序。

更新2

好像,我们需要添加如果(Page.IsValid)按钮点击此外,如果我们使用自定义验证与服务器端验证。请参阅的CustomValidator都不尽如人意

注意:客户端验证的问题就在这里present:<一href=\"http://stackoverflow.com/questions/13832818/whether-to-use-page-isvalid-or-page-clientvalidate-for-client-side-events\">Whether使用Page_IsValid或Page_ClientValidate()(用于客户端活动)

MARKUP

 &LT; HTML的xmlns =htt​​p://www.w3.org/1999/xhtml&GT;
&LT;头=服务器&GT;
&LT;标题&GT;&LT; /标题&GT;
&LT;脚本类型=文/ JavaScript的&GT;
    警报('HAIII');
&LT; / SCRIPT&GT;&LT; /头&GT;
&LT;身体GT;
&LT;表ID =form1的=服务器&GT;
&LT; D​​IV&GT;
    &LT; ASP:的ValidationSummary =服务器ID =vsumAllDISPLAYMODE =BulletList的CssClass =的ValidationSummary的ValidationGroup =ButtonClick/&GT;
    &LT; ASP:文本框ID =txtEmpName=服务器&GT;&LT; / ASP:文本框&GT;
    &LT; ASP:的RequiredFieldValidator ID =valEmpName=服务器的ControlToValidate =txtEmpName
        EnableClientScript =假的ErrorMessage =的RequiredFieldValidator文本=*显示=动态
        的ValidationGroup =ButtonClick&GT;&LT; / ASP:&的RequiredFieldValidator GT;
    &LT; ASP:按钮的ID =Button1的=服务器的onclick =的button1_Click文本=按钮的ValidationGroup =ButtonClick/&GT;
&LT; / DIV&GT;
&LT; /表及GT;
&LT; /身体GT;
&LT; / HTML&GT;

code背后

 保护无效的button1_Click(对象发件人,EventArgs的发送)
{
    字符串值= txtEmpName.Text;
    SubmitEmployee(值);
}

参考


  1. 我应该始终调用Page.IsValid?

  2. ASP.NET验证控件 - 要点,技巧和窍门

  3. 的CustomValidator都不尽如人意


解决方案

确认后发生的Page_Load ,但在此之前的事件处理程序(请参阅http://msdn.microsoft.com/en-us/library/ms178472(v=VS.100).aspx).

如果您的按钮不会导致验证,则必须手动触发 Page.Validate。

您可能没有询问 Page.IsValid 后才(1)你叫 Page.Validate 或(2 ),导致验证的控件是包含在回发源/

如果您需要验证事件处理程序开火之前发生的,你可以使用:

 如果(Page.IsPostback)
{
   Page.Validate(/ *控制验证组名称可选* /);
   如果(Page.IsValid)
   {
       //做一些很酷的东西
   }
}

您可能还需要考虑重新设计,所以你不这样做必须的。

在处理引起的验证,控制事件处理程序 Page.IsValid 保证是可用的。在所有其他情况下,它通常是更安全的重新请求验证。

:对于具有验证一个表单提交处理一个模型

 无效btnSubmit_Click(对象发件人,EventArgs的发送)
{
   this.UpdateGUIWithSubmitRequest();
   如果(Page.IsValid)
   {
      this.ProcessSuccessfulSubmission();
   }
   其他
   {
      this.ProcessInvalidSubmission();
   }
}

如果您使用的是的CustomValidator ,有一个非常昂贵的验证步骤,你可以考虑缓存结果在的Htt presponse。缓存,所以你不必仿佛Page.Validate多次调用发生重新验证。

 无效CustomValidator_ServerValidate(对象源,ServerValidateEventArgs参数)
{
   自我的CustomValidator =(的CustomValidator)来源;
   字符串validatorResultKey = self.ClientID;
   布尔? validatorResult = Context.Items [validatorResultKey]作为布尔?;
   如果(validatorResult.HasValue)
   {
      args.IsValid = validatorResult.Value;
      返回;
   }   BOOL的isValid = this.DoSomethingVeryTimeConsumingOrExpensive();
   Context.Items [validatorResultKey] =的isValid;
   args.IsValid =的isValid;
}

这,当然要看100%,你的架构和你是否是能够承担一个合格/不合格初步验证过程中还通过/在同一页生命周期的后续验证失败。验证

I have following code with a RequiredFieldValidator. The EnableClientScript property is set as "false" in the validation control. Also I have disabled script in browser.

I am NOT using Page.IsValid in the code behind. Still, when I submit without any value in textbox I will get error message.

From comments of @Dai, I came to know that this can be an issue, if there is any code in Page_Load that is executed in a postback. There will be no validation errors thrown.

(However, for button click handler, there is no need to check Page.IsValid)

if (Page.IsPostBack)
{
    string value = txtEmpName.Text;
    txtEmpName.Text = value + "Appended";
}

QUESTION

  1. Why does not the server side validation happen before Page_Load?
  2. Why does it work fine when I use Page.IsValid?
  3. Can you provide any reference to an article that explains this? (Not something that says - always use Page.IsValid; but something that says what are the mandatory scenarios to use Page.IsValid

UPDATE 1

Refer ASP.NET Validators Common Misconception

Page.IsValid is accessible only after running Page.Validate() method which is invoked implicitly somewhere after Page_Load. In case you keep all of your logic in a Page_Load event handler (which is highly discouraged!), call the Page.Validate() before checking the Page.IsValid.

Note: It is advised not to keep all the logic in Page_Load. If something is to happen on button click event, move it to button click event handler. If something is to happen on drop-down event, move it to drop-down selected item change event handler.

UPDATE 2

It seems like, we need to add If(Page.IsValid) in button click also if we are using a Custom Validator with server side validation. Refer CustomValidator not working well.

Note: Client side validation question is present here: Whether to use Page_IsValid or Page_ClientValidate() (for Client Side Events)

MARKUP

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
    alert('haiii');
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
    <asp:ValidationSummary runat="server" ID="vsumAll" DisplayMode="BulletList" CssClass="validationsummary" ValidationGroup="ButtonClick" />
    <asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="valEmpName" runat="server" ControlToValidate="txtEmpName"
        EnableClientScript="false" ErrorMessage="RequiredFieldValidator" Text="*" Display="Dynamic"
        ValidationGroup="ButtonClick"></asp:RequiredFieldValidator>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" ValidationGroup="ButtonClick" />
</div>
</form>
</body>
</html>

CODE BEHIND

protected void Button1_Click(object sender, EventArgs e)
{
    string value = txtEmpName.Text;
    SubmitEmployee(value);
}

References:

  1. Should I always call Page.IsValid?
  2. ASP.NET Validation Controls – Important Points, Tips and Tricks
  3. CustomValidator not working well

解决方案

Validation occurs after Page_Load, but before event handlers (See http://msdn.microsoft.com/en-us/library/ms178472(v=VS.100).aspx).

If your button does not cause validation, you must manually fire Page.Validate.

You may not interrogate Page.IsValid until after (1) you have called Page.Validate or (2) a control that causes validation was the source of/included in a postback.

If you require validation to occur before event handlers fire, you may use:

if (Page.IsPostback) 
{
   Page.Validate( /*Control Validation Group Name Optional*/ );
   if (Page.IsValid)
   {
       //Do some cool stuff
   }
}

You may also want to consider redesigning so you aren't required to do so.

In an event handler that handles a control which causes validation, Page.IsValid is guaranteed to be available. In all other cases, it is generally safer to re-request validation. One model for handling submissions on a form that has validators:

void btnSubmit_Click(object sender, EventArgs e)
{
   this.UpdateGUIWithSubmitRequest();
   if (Page.IsValid)
   {
      this.ProcessSuccessfulSubmission();
   }
   else
   {
      this.ProcessInvalidSubmission();
   }
}

If you are using a CustomValidator that has a very expensive validation step, you may consider caching the result in the HttpResponse.Cache so you do not have to re-validate if multiple calls to Page.Validate occur.

void CustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
   CustomValidator self = (CustomValidator)source;
   string validatorResultKey = self.ClientID;
   bool? validatorResult = Context.Items[validatorResultKey] as bool?;
   if (validatorResult.HasValue)
   {
      args.IsValid = validatorResult.Value;
      return;
   }

   bool isValid = this.DoSomethingVeryTimeConsumingOrExpensive();
   Context.Items[validatorResultKey] = isValid;
   args.IsValid = isValid;
}

This, of course, depends 100% on your architecture and whether or not you are able to assume that a passed/failed validation during initial validation still passes/fails during subsequent validations of the same Page Life Cycle.

这篇关于如何Page.IsValid工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆