【问题标题】:asp.net C# update textbox value without refreshasp.net C#更新文本框值而不刷新
【发布时间】:2020-05-17 16:45:20
【问题描述】:

我有一个网站,其中有两个页面,page1 包含 textbox 和 button1,

如果我点击了button1,它将打开包含button2的page2,

如果我点击了 button2,它会将 page2 中的值分配给 page1 中的文本框

但问题是刷新page1后值会显示在文本框中,

我的问题是如何在 page2 中单击 button2 后直接更新文本框值而不在 page1 中刷新,如下所示:

这是我的代码:

page1 aspx.cs:

<script type="text/javascript">

function openPopup() {

    window.open("page2.aspx", "_blank", "WIDTH=1080,HEIGHT=790,scrollbars=no, menubar=no,resizable=yes,directories=no,location=no");

}

<asp:button text="clik" id="button1" runat="server" onclientclick="return openPopup()" xmlns:asp="#unknown" style="margin-right:30%" />



    protected void Page_Load(object sender, EventArgs e)
    {

       if (Session["userID"] != null)
                {
                    txtbox.Text = HttpContext.Current.Session["userID"].ToString();
                }
    }

第 2 页:

   protected void button2(object sender, EventArgs e)
    {
      Session["userID"] = row.Cells[0].Text;
    }

【问题讨论】:

  • 为 Label 设置 AutoPostBack true 并将 UpdateMode 属性设置为 Conditional
  • 感谢 Samim Hussain 我回答了你的问题,但它没有用。

标签: c# asp.net


【解决方案1】:

我们可以通过以下方式做到这一点:

  1. 在第 2 页创建一个 javascript 函数,用于刷新 textbox1 第 1 页。
  2. 从第 2 页单击按钮 2,使用脚本管理器,调用 在第 1 步中使用 require 参数创建的函数。

所以,基本上你的代码是这样的:

 // place this in page2.aspx
 // javascript function to update text box in page 1;
  function UpdateParentText(value){  
     if(typeof(value) != undefined){
        window.opener.document.getElementById("TextBox1").value=value;
      }
   }

  //2. code behind call to the javascript function from page2.cs
  protected void button2(object sender, EventArgs e)
    {
    // code behind call to the javascript function. 
    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "MyScript", "UpdateParentText('" + row.Cells[0].Text + "'", true);
   }

如果你不使用 AJAX,那么使用这个:

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript", "UpdateParentText('" + row.Cells[0].Text + "'", true);

【讨论】:

  • 感谢 Rishu Ranjan 的回答我尝试了代码但仍然没有更新 TextBox1
  • 嗨,Arater,你能告诉我什么不工作吗?你能调用javascript函数'UpdateParentText'吗?
  • 我尝试了相同的代码,但是当我单击第 2 页中的 button2 时,pag1 中 textbox1 的值不会动态更新我需要刷新 page1 以更新 textbox1 值
  • 我明白了,但你能告诉我是否调用了函数 UpdateParentText 吗?
  • 不叫
【解决方案2】:

你可以使用:

  • window.postMessage() — 发送消息
  • window.addEventListener(“message”,callback) — 接收和处理消息

参见示例here

【讨论】:

    【解决方案3】:

    感谢大家,我通过使用 javascript 会话解决了这个问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-05
      • 1970-01-01
      • 2014-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-22
      相关资源
      最近更新 更多