RadTextBox не обновляется

Привет, я пытаюсь обновить некоторые значения базы данных с помощью простой формы с Telerik RadTextBoxes. Я могу установить текстовое значение без проблем, но когда дело доходит до сохранения при нажатии кнопки, значения не обновляются. Мой код для установки текстового поля находится в функции загрузки страницы, однако я проверяю, если (! IsPostBack)

Вот мой html:

<div style="width:95%;">
<div style=" width:100%;float:left; background-color:#fff; border:1px solid #d1d2d3; margin-top:25px; padding:15px; -webkit-box-shadow: inset 1px 0px 5px 0px rgba(50, 50, 50, 0.10); -moz-box-shadow:    inset 1px 0px 5px 0px rgba(50, 50, 50, 0.10); box-shadow: inset 1px 0px 5px 0px rgba(50, 50, 50, 0.10);">
    <h2 style="float:left; width:50%;"><asp:Literal ID="litTitle" runat="server" Text="Add A New Zone" /></h2>
    <telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" Width="100%">
        <telerik:RadNotification runat="server" id="notifyError" Position="Center" Width="330" Height="130" EnableRoundedCorners="true" EnableShadow="true" Style="z-index: 35000"></telerik:RadNotification>

        <div style="float:right;margin-right:10px;margin-left:5px;"><telerik:RadButton ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" /></div><div style="float:right;margin-right:5px;"><telerik:RadButton ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" /></div><div style="float:right;margin-right:5px;"><telerik:RadButton ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" OnClientClicked="confirm('Are you sure you wish to delete this zone?');" /></div>
        <div class="clear" style="clear:both;height:25px;"></div>
        <div style="width:100%;">
            <div style="float:left;">
                <div style="float:left; margin-left:10px; margin-right:5px; width:200px;">Zone Code:</div>
                <div style="float:left; margin-left:5px; margin-right:10px;"><telerik:RadTextBox ID="txtZoneName" runat="server" CausesValidation="false" Width="200"></telerik:RadTextBox></div>
            </div>
            <div class="clear" style="height:35px;clear:both;"></div>
            <div style="float:left;">
                <div style="float:left; margin-left:10px; margin-right:5px; width:200px;">Name:</div>
                <div style="float:left; margin-left:5px; margin-right:10px;"><telerik:RadTextBox ID="txtZoneCode" runat="server" CausesValidation="false" Width="200"></telerik:RadTextBox></div>
            </div>
            <div class="clear" style="height:35px;clear:both;"></div>
            <div>
                <div style="float:left; margin-left:10px; margin-right:5px; width:200px;">Monthly Book Page Goal:</div>
                <div style="float:left; margin-left:5px; margin-right:10px;"><telerik:RadTextBox ID="txtZoneBookGoal" runat="server" CausesValidation="false" Width="200"></telerik:RadTextBox></div>
            </div>
            <div class="clear" style="height:45px;clear:both;"></div>
            <div style="width:250px; margin:0 auto;">
                <div style="float:left;"><telerik:RadButton ID="btnCreate" runat="server" Text="Save" OnClick="btnCreate_Click" /></div>
            </div>
        </div>
    </telerik:RadAjaxPanel>
</div>
</div>

Вот мой С#:

protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
            if(Request.Params["z"] != null)
            {
                Zones z = Zones.GetByID(Utils.GetLong(Request.Params["z"]));

                this.txtZoneCode.Text = z.Code;
                this.txtZoneName.Text = z.Name;
                this.txtZoneBookGoal.Text = Utils.GetString(z.BookGoal);
                this.litTitle.Text = "Edit Zone";
            }
        }
    }

protected void btnSave_Click(object sender, EventArgs e)
    {
        bool valid = true;
        string error = "";

        if (this.txtZoneCode.Text == "")
        {
            valid = false;
            error += "- Code<br/>";
        }

        if (this.txtZoneName.Text == "")
        {
            valid = false;
            error += "- Name<br/>";
        }

        if (valid)
        {
            if (Request.Params["z"] != null)
            {
                Zones z = Zones.GetByID(Utils.GetLong(Request.Params["z"]));

                z.Code = this.txtZoneCode.Text;
                z.Name = this.txtZoneName.Text;
                z.BookGoal = Utils.GetInt(this.txtZoneBookGoal.Text);

                z.Save();

                if (z.ZoneID > 0)
                {
                    Response.Redirect("ManageZones.aspx?v=1", true);
                }
                else
                {
                    this.notifyError.Title = "Zone update was not successfull!";
                    this.notifyError.Text = "There was an error saving your zone. Please try again";
                    this.notifyError.Show();
                    return;
                }
            }
            else
            {
                Zones z = new Zones();

                z.Code = this.txtZoneCode.Text;
                z.Name = this.txtZoneName.Text;
                z.BookGoal = Utils.GetInt(this.txtZoneBookGoal.Text);

                z.Save();

                if (z.ZoneID > 0)
                {
                    Response.Redirect("ManageZones.aspx?v=1", true);
                }
                else
                {
                    this.notifyError.Title = "Zone creation was not successfull!";
                    this.notifyError.Text = "There was an error saving your zone. Please try again";
                    this.notifyError.Show();
                    return;
                }
            }
        }
        else
        {
            this.notifyError.Title = "Please fill in the following to continue:";
            this.notifyError.Text = error;
            this.notifyError.Show();
            return;
        }
    }

Роберт Зено


person Robert Zeno    schedule 04.02.2015    source источник


Ответы (2)


Я изменил OnClientClicked на OnClientClicking, потому что произошла ошибка javascript, из-за которой страница сломалась и не извлекла правильные данные.

person Robert Zeno    schedule 06.02.2015

У вас есть четыре кнопки - две кнопки имеют одинаковое имя Сохранить.

Похоже, вы нажимаете неправильно. Меня это тоже смущает.

protected void btnSave_Click(object sender, EventArgs e)
{
   // Not this event
}

protected void btnCreate_Click(object sender, EventArgs e)
{
   // You need to use this event.
}

Для лучшей практики проектирования

  1. Используйте CSS вместо встроенных стилей.
  2. Вам нужно правильно назвать кнопки. Например, СохранитьRadButton, СоздатьRadButton

НЕ используйте венгерскую нотацию, например btnXXX, особенно при использовании сторонних элементов управления. как телерик.

person Win    schedule 04.02.2015
comment
Я не нажимаю неправильную кнопку. У меня есть два события кликов. Я слежу за точками останова и наблюдаю, как они попадают в их уважаемые события нажатия кнопок. - person Robert Zeno; 05.02.2015
comment
Я понятия не имею, что такое класс Zones. Вам необходимо выполнить отладку через класс Zones. - person Win; 05.02.2015
comment
зачем мне отлаживать Зоны? Текстовое поле не обновляется. Я удалил всю венгерскую нотацию и правильно назвал кнопки, но все равно не обновляюсь. - person Robert Zeno; 06.02.2015
comment
The textbox is not updating Что вы имеете в виду под не обновлять? Вы имеете в виду, что txtZoneCode.Text и txtZoneName.Text пусты внутри события btnSave_Click при построчной отладке? - person Win; 06.02.2015
comment
Нет, они с исходными установленными значениями при загрузке страницы. Я ничего не печатаю - person Robert Zeno; 06.02.2015
comment
Не могли бы вы установить точку останова внутри события Page_Load и проверить код внутри if(!Page.IsPostBack) после обратной передачи? - person Win; 06.02.2015
comment
Работает отлично. Код верен, когда Page.IsPostBack нажимается после нажатия кнопки сохранения - person Robert Zeno; 06.02.2015
comment
Я изменил OnClientClicked на OnClientClicking и написал подтверждение таким образом, и это сработало. Был перерыв в javascript для OnClientClicked. Спасибо за вашу помощь, хотя - person Robert Zeno; 06.02.2015
comment
Не проблема. Я рад, что ты разобрался. - person Win; 07.02.2015