Страница asp.net не отправляет назад, в то время как событие нажатия кнопки все еще срабатывает - PullRequest
0 голосов
/ 29 февраля 2012

Хорошо, у меня есть эта страница, на которой есть один Ajax:AsyncFileUploader, а также некоторые другие элементы Ajax, такие как ModelPopUpExtender и т. Д. Проблема в двух кнопках на странице, Cancel и Submit, обе запускается , но никто не отправляет обратно, хотя я убедился, что ни одно из полей на странице не пусто.

Я знаю, что события запускаются, потому что я отлаживал JavaScript в Firebug (один шаг в и продолжить процесс занял более 4 минут, в то время как я просто держал клавишу F10 для входа,вниз!)

Если кому-то нужен код, пожалуйста, скажите, что я опубликую его, но кнопки просто в обычном коде, так что ничего особенного, поэтому я не публикую код, но в случае необходимости могу выложитькод всей страницы (который является довольно длинным Я бы сказал вам, хотя на самом деле, но, по крайней мере, просто для публикации здесь, примерно в 200 строк).Кто-нибудь может помочь?

Редактировать: В соответствии с комментарием я отправляю код
код: aspx page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
    Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Detailed Reminder</title>
    <link href="StyleSheets/Default.css" rel="stylesheet" type="text/css" />

    <script type="text/javascript">

        function FileUploaded(sender, args) {
            var filename = args.get_fileName();
            var contentType = args.get_contentType();
            var text = "Size of " + filename + " is " + args.get_length() + " bytes";
            if (contentType.length > 0) {
                text += " and content type is '" + contentType + "'.";
            }
            $get('LabelStatusUpload').innerHTML = "File Uploaded Successfully";
        }

        function UploadStarted(sender, args) {
            $get('LabelStatusUpload').innerHTML = "Upload Started";
        }

        function ErrorUploaded(sender, args) {
            $get('LabelStatusUpload').innerHTML = "Some Error Occured";
        }

    </script>

</head>
<body>
    <form id="Form1" runat="server">
    <ajax:ToolkitScriptManager ID="SM1" runat="server">
    </ajax:ToolkitScriptManager>
    <asp:Button ID="Temp1" runat="server" Text="clear" />
    <div id="UpperContainer">
        <asp:Panel ID="PanelOuter" runat="server">
            <asp:Table ID="TableDetailedRemidner" runat="server">
                <asp:TableRow ID="TableRowName" runat="server">
                    <asp:TableCell ID="TableCell1" runat="server">
                        <asp:Label ID="LabelName" runat="server" AssociatedControlID="txtName" Text="Name"></asp:Label>
                    </asp:TableCell>
                    <asp:TableCell ID="TableCell2" runat="server">
                        <asp:TextBox ID="txtName" runat="server" ToolTip="Name of the user to send the mail to"></asp:TextBox>
                    </asp:TableCell>
                </asp:TableRow>
                <asp:TableRow ID="TableRowEmail" runat="server">
                    <asp:TableCell ID="TableCell3" runat="server">
                        <asp:Label ID="LabelEmail" runat="server" AssociatedControlID="txtEmail1" Text="Email 1"></asp:Label>
                    </asp:TableCell>
                    <asp:TableCell ID="TableCell4" runat="server">
                        <asp:TextBox ID="txtEmail" runat="server" Width="560px"></asp:TextBox>
                        <asp:RegularExpressionValidator ID="regexEmailValidator" runat="server" ControlToValidate="txtEmail"
                            Display="Dynamic" Text="Invalid Email" ValidationExpression="\w+([-+.’]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
                    </asp:TableCell>
                </asp:TableRow>
                <asp:TableRow ID="TableRowSubject" runat="server">
                    <asp:TableCell ID="TableCell5" runat="server">
                        <asp:Label ID="LabelSubject" runat="server" AssociatedControlID="txtSubject" Text="Subject"></asp:Label>
                    </asp:TableCell>
                    <asp:TableCell ID="TableCell6" runat="server">
                        <asp:TextBox ID="txtSubject" runat="server" AutoComplete="off" Width="560px"></asp:TextBox>
                        <asp:Panel ID="PanelDefaultSubjects" runat="server">
                            <div>
                                <asp:UpdatePanel ID="UpdatePanelSubject" runat="server">
                                    <ContentTemplate>
                                        <asp:RadioButtonList ID="RadioSubjectList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="RadioSubjectList_SelectedIndexChanged">
                                            <asp:ListItem Text="Submit the reports"></asp:ListItem>
                                            <asp:ListItem Text="prepare the presentation"></asp:ListItem>
                                            <asp:ListItem Text="Custom" Value=""></asp:ListItem>
                                        </asp:RadioButtonList>
                                    </ContentTemplate>
                                </asp:UpdatePanel>
                            </div>
                        </asp:Panel>
                        <ajax:PopupControlExtender ID="PCESubject" runat="server" TargetControlID="txtSubject"
                            PopupControlID="PanelDefaultSubjects" CommitProperty="value" Position="Right"
                            OffsetX="5" CommitScript="e.value" />
                    </asp:TableCell>
                </asp:TableRow>
                <asp:TableRow ID="TableRowMessage" runat="server">
                    <asp:TableCell ID="TableCell7" runat="server">
                        <asp:Label ID="LabelMessageBody" runat="server" AssociatedControlID="txtMessageBody"
                            Text="Message"></asp:Label>
                    </asp:TableCell>
                    <asp:TableCell ID="TableCell8" runat="server">
                        <asp:TextBox ID="txtMessageBody" runat="server" Columns="40" Rows="10" Multiline="true"></asp:TextBox>
                    </asp:TableCell>
                </asp:TableRow>
                <asp:TableRow ID="TableRowFileUpload" runat="server">
                    <asp:TableCell ID="TableCell9" runat="server">
                        <asp:Label ID="LabelFileAttached" runat="server" AssociatedControlID="AsyncFileUpload1"
                            Text="Attach a file"></asp:Label>
                    </asp:TableCell>
                    <asp:TableCell ID="TableCell10" runat="server">
                        <ajax:AsyncFileUpload ID="AsyncFileUpload1" runat="server" OnClientUploadComplete="FileUploaded"
                            OnClientUploadError="ErrorUploaded" OnClientUploadStarted="UploadStarted" OnUploadedComplete="File_Uploaded"
                            UploaderStyle="Modern" ThrobberID="LabelThobber" />
                        <asp:Label ID="LabelThobber" runat="server" Style="display: none"><img alt="" src="Images/uploading.gif" /></asp:Label><br />
                        <asp:Label ID="LabelStatusUpload" runat="server" Text="    "></asp:Label>
                    </asp:TableCell>
                </asp:TableRow>
                <asp:TableRow ID="TableRowDueDate" runat="server">
                    <asp:TableCell ID="TableCell11" runat="server">
                        <asp:Label ID="LabelDueDate" runat="server" AssociatedControlID="txtDueDate" Text="Due Date"></asp:Label>
                    </asp:TableCell>
                    <asp:TableCell ID="TableCell12" runat="server">
                        <asp:TextBox ID="txtDueDate" runat="server" Width="560px"></asp:TextBox>
                        <ajax:MaskedEditExtender runat="server" ID="MEEDueDate" TargetControlID="txtDueDate"
                            Mask="99/99/9999" AutoComplete="true" MaskType="Date">
                        </ajax:MaskedEditExtender>
                        <ajax:MaskedEditValidator ID="MEVDueDate" runat="server" ControlExtender="MEEDueDate"
                            ControlToValidate="txtDueDate" IsValidEmpty="False" EmptyValueMessage="Due Date is required"
                            InvalidValueMessage="Due Date is required" EmptyValueBlurredText="*" InvalidValueBlurredMessage="*"
                            MaximumValueBlurredMessage="*" MinimumValueBlurredText="*" Display="Dynamic" />
                        <ajax:CalendarExtender ID="CalDueDate" runat="server" TargetControlID="txtDueDate">
                        </ajax:CalendarExtender>
                    </asp:TableCell></asp:TableRow>
                <asp:TableRow ID="TableRowFrequency" runat="server">
                    <asp:TableCell ID="TableCell17" runat="server">
                        <asp:Label ID="LabelFrequency" runat="server" AssociatedControlID="txtFrequency"
                            Text="Frequency"></asp:Label>
                    </asp:TableCell><asp:TableCell ID="TableCell18" runat="server">
                        <asp:TextBox ID="txtFrequency" runat="server"></asp:TextBox>
                        <asp:Panel ID="PanelFrequency" runat="server">
                            <div>
                                <asp:UpdatePanel ID="UpdatePanelFrequency" runat="server">
                                    <ContentTemplate>
                                        <asp:RadioButtonList ID="RadioButtonFrequency" runat="server" AutoPostBack="true"
                                            OnSelectedIndexChanged="RadioSubjectFrequency_SelectedIndexChanged">
                                            <asp:ListItem Text="15 min"></asp:ListItem>
                                            <asp:ListItem Text="6 hr"></asp:ListItem>
                                            <asp:ListItem Text="24 hr"></asp:ListItem>>
                                        </asp:RadioButtonList>
                                    </ContentTemplate>
                                </asp:UpdatePanel>
                            </div>
                        </asp:Panel>
                        <ajax:PopupControlExtender ID="PCEFrequency" runat="server" TargetControlID="txtFrequency"
                            PopupControlID="PanelFrequency" CommitProperty="value" Position="Right" OffsetX="5"
                            CommitScript="e.value" />
                    </asp:TableCell></asp:TableRow>
                <asp:TableFooterRow>
                    <asp:TableCell ID="TableCellSubmit" runat="server">
                        <asp:Button ID="BtnSubmit" runat="server" OnClick="Submit_Click" Text="Set Reminder Detailed" />
                    </asp:TableCell><asp:TableCell ID="TableCellCancel" runat="server">
                        <asp:Button ID="BtnCancel" runat="server" OnClick="Cancel_Click" Text="Cancel" />
                    </asp:TableCell></asp:TableFooterRow>
            </asp:Table>
        </asp:Panel>
    </div>
    </form>
</body>
</html>

Код: page_Behind.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    //static protected string savePath;
    //static protected int curFileSize;
    //static protected bool IsFileAttached;

    protected void Page_Load(object sender, EventArgs e)
    {
        CalDueDate.StartDate = DateTime.Now.Date;
        CalDueDate.EndDate = DateTime.Now.Date.AddYears(1);
        MEVDueDate.MinimumValue = DateTime.Now.Date.ToShortDateString();
        MEVDueDate.MaximumValue = DateTime.Now.Date.ToShortDateString();
    }

    protected void RadioSubjectList_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(RadioSubjectList.SelectedValue))
        {
            // Popup result is the selected task
            PCESubject.Commit(RadioSubjectList.SelectedValue);
        }
        else
        {
            // Cancel the popup
            PCESubject.Cancel();
        }
        // Reset the selected item
        RadioSubjectList.ClearSelection();
    }

    protected void RadioSubjectFrequency_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(RadioButtonFrequency.SelectedValue))
        {
            PCEFrequency.Commit(RadioButtonFrequency.SelectedValue);
        }
        else
        {
            PCEFrequency.Cancel();
        }
        RadioButtonFrequency.ClearSelection();
    }

    protected void File_Uploaded(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
    {
        if (AsyncFileUpload1.HasFile)
        {
            string savePath = MapPath("~/Uploads/") + Path.GetFileName(DateTime.Now.Month + DateTime.Now.Day + " "
                                                                            + DateTime.Now.Hour + DateTime.Now.Minute + " " + e.FileName);
            AsyncFileUpload1.SaveAs(savePath);
        }
    }

    protected void Submit_Click(object sender, EventArgs e)
    {
        // On Submit button doesn't even reaches here, debugged and breakpoint on any of following code is never reached
        int lastID = BusinessLayer.DetermineLastDetailedID();
        // Some other logic unimportant at this point
        BusinessLayer.AddDReminder(sender, e);
    }

    protected void Cancel_Click(object sender, EventArgs e)
    {
        txtName.Text = "";
        txtEmail1.Text = "";
        txtEmail2.Text = "";
        txtEmail3.Text = "";
        txtSubject.Text = "";
        txtMessageBody.Text = "";
        txtDueDate.Text = "";
        txtFrequency.Text = "";

    }

}

Ответы [ 3 ]

1 голос
/ 09 марта 2012

Я скопировал ваш код, испытал проблему, исправил ее, и теперь обратная передача происходит нормально. MEVDueDate всегда говорит «IsValid = false», и из-за этого PostBack не доходил до Page_Load (это ожидаемое поведение этого валидатора).

Вам необходимо изменить:

MEVDueDate.MinimumValue = DateTime.Now.Date.ToShortDateString();
MEVDueDate.MaximumValue = DateTime.Now.Date.ToShortDateString();

с этим:

MEVDueDate.MinimumValue = DateTime.Now.Date.ToString("MM/dd/yyyy");
MEVDueDate.MaximumValue = DateTime.Now.Date.ToString("MM/dd/yyyy");

Выберите сегодня в календаре срок исполнения, нажмите кнопку «Отмена», и вы получите полный постбэк. Пожалуйста, обратите внимание, что вы говорите, что минимальные и максимальные допустимые даты - оба сегодня, поэтому сегодня - единственная действительная дата, которая разрешит отправку обратно.

Причина заключается в том, что средство выбора календаря пишет в текстовое поле "03/08/2012", но ToShortDateString () получает строку с другим форматом даты. В итоге вы сравниваете «03/08/2012» с «08/03/2012».

Вам необходимо убедиться, что формат даты, который вы используете для установки MEVDueDate.MinimumValue, соответствует формату, который CalendarPicker (CalDueDate) помещает в txtDueDate.

0 голосов
/ 08 марта 2012

События кнопок не распространяются из объекта Table, в котором они содержатся.

Зарегистрируйте события OnClick для 2 кнопок при создании таблицы.

0 голосов
/ 07 марта 2012
 comment this and try 



   <%-- <ajax:MaskedEditExtender runat="server" ID="MEEDueDate" TargetControlID="txtDueDate"
                        Mask="99/99/9999" AutoComplete="true" MaskType="Date">
                    </ajax:MaskedEditExtender>
                    <ajax:MaskedEditValidator ID="MEVDueDate" runat="server" ControlExtender="MEEDueDate"
                        ControlToValidate="txtDueDate" IsValidEmpty="False" EmptyValueMessage="Due Date is required"
                        InvalidValueMessage="Due Date is required" EmptyValueBlurredText="*" InvalidValueBlurredMessage="*"
                        MaximumValueBlurredMessage="*" MinimumValueBlurredText="*" Display="Dynamic" />
                    <ajax:CalendarExtender ID="CalDueDate" runat="server" TargetControlID="txtDueDate">
                    </ajax:CalendarExtender>--%>
...