如果服务器端验证失败,则在OnClick事件中显示警报

时间:2014-02-04 00:54:13

标签: javascript asp.net validation

我有一个在“保存”按钮上定义了OnClick事件的ASP.NET页面。我想实现这样的行为:

protected void SaveButton_Click(object sender, EventArgs e)
{
    // Validate state on server side
    // ...
    if (isValid)
    {
        // Save the settings
    }
    else
    {
        // Display alert with error meessage
    }
}

如上面的评论中所述,我需要对系统状态执行一些服务器端验证。如果发生任何错误,我需要立即显示警告对话框(最好不要重新加载页面)。

我尝试使用RegisterClientScriptBlockRegisterStartupScript注册一些Javascript以在页面中运行,但它似乎没有按照我的意愿行事。

听起来我需要将它们放在Page_Load中,以便Javascript在前面注册,但我还需要确保如果所有内容都有效,则不会显示错误。问题是,如果我将警报注册到Page_Load,警报会在我们有机会验证所有内容之前出现,并确保一切正常。

我认为我可以在表单中放置一个隐藏字段,我可以将其用作标记,以指示事物是否有效,但页面的生命周期正在我的头脑中,我似乎无法想象了解如何使其正常工作。

我真正需要的是某种服务器端验证事件,可以在SaveButton_Click之前启动,它可以设置隐藏的表单字段,指示一切是否正常,然后我可以让我的Javascript注册依赖于这个隐藏领域的价值。

这可能吗?还有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

我不记得我在哪里发现了这个小小的jem,但我有一个警报类,我可以从后面的代码中调用它。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

/// <summary>
/// Summary description for Alert
/// </summary>
public static class Alert
{

    /// <summary>
    /// Shows a client-side JavaScript alert in the browser.
    /// </summary>
    /// <param name="message">The message to appear in the alert.</param>
    public static void Show(string message)
    {
        // Cleans the message to allow single quotation marks
        string cleanMessage = message.Replace("'", "\\'");
        string script = "<script type=\"text/javascript\">alert('" + cleanMessage     + "');</script>";

        // Gets the executing web page
        Page page = HttpContext.Current.CurrentHandler as Page;

        // Checks if the handler is a Page and that the script isn't allready on the Page
        if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
        {
            page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
        }
    }
    public static void Show(string message, string redirect)
    {
        // Cleans the message to allow single quotation marks
        string cleanMessage = message.Replace("'", "\\'");
        string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');window.location.href='"+redirect+"'</script>";

        // Gets the executing web page
        Page page = HttpContext.Current.CurrentHandler as Page;

        // Checks if the handler is a Page and that the script isn't allready on the Page
        if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
        {
            page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
        }
    }
}

然后作为我的try / catch语句的一部分调用为

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
    try
    {

        //blah blah, some data access suff


    }
    catch (Exception ex)
    {

        Alert.Show(ex.Message);
    }
相关问题