首页 > 解决方案 > 单击 ASP:Button 时获取 ASP:TextBox 的值

问题描述

我知道这是一个愚蠢的问题,而且是一个简单的问题,但我觉得我快疯了,因为我无法让它工作(即使我以前做过一百万次)。

我的 ASP.NET 页面中有一个文本框和一个按钮

                <asp:TextBox ID="commentTextBox" inputtype="text" runat="server" CssClass="uk-textarea"></asp:TextBox>
                <asp:Button ID="buttonComment" runat="server" CssClass="uk-button uk-button-text" text="Post Comment" OnClick="buttonComment_Click" />

这些是更大的 HTML 标记集的一部分,包含在:

<form id="form1" runat="server">

单击按钮时,我执行以下操作(获取文本框的值并将其作为“评论”发布到数据库)

    protected void buttonComment_Click(object sender, EventArgs e)
    {
        try
        {
            //string commentText = ((TextBox)FindControl("Comment")).Text;
            string strDate = Request.Form["commentTextBox"].ToString();

            Spark.Comment comment = new Spark.Comment
            {
                CommentByEmail = Context.User.Identity.Name.ToString(),
                CommentDate = DateTime.Now,
                SparkId = sparkId,
                CommentText = strDate,
            };

            using (var client = new AmazonLambdaClient(Amazon.RegionEndpoint.APSoutheast2))
            {
                var request = new InvokeRequest
                {
                    FunctionName = ConfigurationManager.AppSettings["lambdaArnPrefix"] + "lambdaSparkCreateComment",
                    Payload = JsonConvert.SerializeObject(comment),
                    InvocationType = InvocationType.RequestResponse
                };

                var response = client.Invoke(request);
            }

            Response.Redirect($"SparkDetail?action=comment");
        }
        catch (Exception ex)
        {
            sparkCardSingle.Text = ex.ToString();
        }
    }

我已经尝试了所有这些获取价值的变体:

string commentText = ((TextBox)FindControl("commentTextBox")).Text

string commentText = Request.Form["commentTextBox"].ToString();

string commentText  = CommentText.Text; 

但无论如何,我在回发时收到此错误

System.NullReferenceException: Object reference not set to an instance of an object. at APISpark.SparkDetail.Page_Load(Object sender, EventArgs e) in C:\Users\jmatson\Source\Repos\Production-Spark-Website\APISpark\SparkDetail.aspx.cs:line 136

我不明白。我觉得我之前已经完成了十亿次代码并且它有效。我不知道为什么它现在不起作用。

标签: htmlasp.netpostback

解决方案


推荐阅读