Casper-SC
@Casper-SC
Программист (.NET)

Не удаётся получить доступ к asp:TextBox из кода. Как получить оттуда значение?

Что я делаю не так? mainContent всегда null. Нужно получить доступ к textBox, что ясно из кода ниже.

Мастер страница:
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs" Inherits="WebAppSendMessage.MasterPage" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <meta charset="utf-8" />
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <div>
        <asp:ContentPlaceHolder ID="MainContentPlaceHolder" runat="server">
        
        </asp:ContentPlaceHolder>
    </div>
</body>
</html>


<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="WebAppSendMessage.Views.Index" %>

<asp:Content ID="header" ContentPlaceHolderID="head" runat="server">
    <style>
        input[type=text] {
            margin-top: 5px;
            margin-left: 3px;
            margin-right: 3px;
            width: 100%;
        }

        input[type=submit] {
            margin-top: 5px;
            margin-left: 3px;
            margin-right: 3px;
        }
    </style>
</asp:Content>

<asp:Content ID="mainContent" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
    <form id="mainForm" runat="server">
        <asp:TextBox ID="textBox" runat="server" />
        <br />
        <asp:Button ID="sendMessageButton" runat="server" Text="Отправить сообщение" OnClick="SendMessageButton_OnClick" />
    </form>
</asp:Content>


using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebAppSendMessage.Views
{
    public partial class Index : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpCookie cookie = Request.Cookies["mainMessage"];
            if (cookie != null)
            {
                textBox.Text = cookie["Message"];
            }
        }

        protected void SendMessageButton_OnClick(object sender, EventArgs e)
        {
            HttpCookie cookie = Request.Cookies["mainMessage"];
            if (cookie == null)
            {
                cookie = new HttpCookie("mainMessage");
                cookie.Expires = DateTime.Now.AddYears(1);
                Response.Cookies.Add(cookie);
                Response.Charset = "utf-8";
            }

            var mainContent = FindControl("MainContentPlaceHolder") as ContentPlaceHolder;
            if (mainContent != null)
            {
                var messageControl = mainContent.FindControl("textBox") as TextBox;
                if (messageControl != null)
                {
                    cookie["Message"] = messageControl.Text;
                }
            }

            Session["BackAddress"] = Request.RawUrl;

            Response.Redirect("Message.aspx");
        }
    }
}
  • Вопрос задан
  • 531 просмотр
Пригласить эксперта
Ответы на вопрос 2
@YaguarVL
.NET developer
Скажите, а для чего вы ищете сначала mainContent, в котором потом пытаетесь найти ваш textBox?
Если ваша задача получить значение из textBox, то не проще ли сделать так? : cookie["Message"] = textBox.Text;

Если же принципиально использовать FindControl, то важно не забывать, что этот метод ищет элемент по ID в пределах текущего контейнера именования. То есть найти textBox можно только вот так:
var control = mainForm.FindControl("textBox");

Если же вы хотите без забот искать элемент на странице, то лучшим вариантом будет рекурсивный перебор коллекции Page.Controls.

Так же в методе Page_Load не лишним будет проверять на nullcookie["Message"] вот так:
if (cookie != null && cookie["Message"] != null)
            {
                textBox.Text = cookie["Message"];
            }

Иначе вас может ждать весьма увлекательная отладка.
Ответ написан
Casper-SC
@Casper-SC Автор вопроса
Программист (.NET)
Решил проблему так:

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="WebAppSendMessage.Views.Index" %>

<asp:Content ID="header" ContentPlaceHolderID="head" runat="server">
    <style>
        input[type=text] {
            margin-top: 5px;
            margin-left: 3px;
            margin-right: 3px;
            width: 100%;
        }

        input[type=submit] {
            margin-top: 5px;
            margin-left: 3px;
            margin-right: 3px;
        }
    </style>
</asp:Content>

<asp:Content ID="mainContent" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
    <form id="mainForm" method="post" runat="server">
        <asp:TextBox ID="textBox" runat="server" />
        <br />
        <asp:Button ID="sendMessageButton" runat="server" Text="Отправить сообщение"  OnClick="SendMessageButton_OnClick"/>
    </form>
</asp:Content>


using System;
using System.Web;
using System.Web.UI;

namespace WebAppSendMessage.Views
{
    public partial class Index : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpCookie cookie = Request.Cookies["mainMessage"];
            
            if (cookie != null)
            {
                string message = cookie["Message"];
                if (message != null)
                {
                    textBox.Text = message;
                }
            }
        }

        protected void SendMessageButton_OnClick(object sender, EventArgs e)
        {
            HttpCookie cookie = Request.Cookies["mainMessage"];
            if (cookie == null)
            {
                cookie = new HttpCookie("mainMessage");
                cookie.Expires = DateTime.Now.AddYears(1);
            }

            string message = Request.Form[textBox.UniqueID];
            cookie["Message"] = message;
            Session["Message"] = message;
            Session["BackAddress"] = Request.RawUrl;

            Response.Charset = "utf-8";
            Response.Cookies.Add(cookie);

            Response.Redirect("Message.aspx");
        }
    }
}


<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"
    CodeBehind="Message.aspx.cs" Inherits="WebAppSendMessage.Views.Message" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
    <form id="mainForm" runat="server">
        <asp:Label runat="server" Text="<%# Text %>"></asp:Label>
        <br />
        <asp:Button ID="backButton" runat="server" Text="Вернуться" OnClick="GoToBackButton_OnClick" />
    </form>
</asp:Content>


using System;
using System.Web;
using System.Web.UI;

namespace WebAppSendMessage.Views
{
    public partial class Message : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataBind();
            }
        }

        protected string Text
        {
            get { return (string)Session["Message"]; }
        }

        protected void GoToBackButton_OnClick(object sender, EventArgs e)
        {
            string returnUrl = Session["BackAddress"] as string ?? "Index.aspx";
            Response.Redirect(returnUrl);
        }
    }
}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы