如何在使用C#按钮单击事件后避免页面刷新 [英] How to avoid page refresh after button click event using C#

查看:589
本文介绍了如何在使用C#按钮单击事件后避免页面刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用c#动态创建100个按钮,但是当我每次点击按钮页面刷新时,我想避免使用C#进行页面刷新,PLZ提供一些解决方案...

提前感谢。



我的尝试:



I have create 100 buttons dynamically using c#, but when i click on button Page refresh every time, i want to avoid page refresh using C#, plz provide some solution...
Thanks in advance.

What I have tried:

protected void Page_Load(object sender, EventArgs e)
    {
        HtmlTable myTable = new HtmlTable();
        int n = 0;
        for (int i = 0; i < 20; i++)
        {

            HtmlTableRow row = new HtmlTableRow();
            for (int c = 1; c <= 5; c++)
            {
                n = (5 * i) + c;
                HtmlTableCell cell = new HtmlTableCell();
                Button btn = new Button();
                btn.Text = n.ToString();
                btn.ID = n.ToString();
                //btn.BackColor = Color.Transparent;
                btn.Width = 30;
                btn.Height = 25;
                btn.Click += new EventHandler(btn_Click);
                cell.Controls.Add(btn);
                row.Controls.Add(cell);
                myTable.Controls.Add(row);
                cell.Attributes.Add("Class", "htTableCellCss");
            }
            row.Attributes.Add("Class", "htTableRowCss");
        }
        myTable.Attributes.Add("Class", "htTableCss");
        PlaceHolder1.Controls.Add(myTable);
    }

    public void btn_Click(object sender, EventArgs e)
    {
        Response.Write(((sender) as Button).Text);
        Button btn = sender as Button;
        btn.BackColor = Color.Green;
        
    }

推荐答案

永远不能使用C#阻止浏览器刷新页面,这只是不是C#的意思。相反,您需要使用JavaScript,然后处理页面刷新事件以取消它。

You can never use C# to prevent the browser from refreshing the page, that is just not what C# is meant to do. Instead, you need to use JavaScript and then handle the page refresh event to cancel it.


#yourBtn)。点击( function (){
// 例如,在按钮的click事件中
event.preventDefault(); // 停止默认操作,即发布
});
("#yourBtn").click(function() { // For example, in the click event of your button event.preventDefault(); // Stop the default action, which is to post });



这样,您可以阻止页面刷新。但是,然后发布内容(如果有要求),您将需要使用Ajax请求发送该数据。



但是,如果您仍想这样做,那么您可能希望将脚本注册到该按钮,反过来(使用JavaScript)会阻止页面重新加载。


This way, you can prevent the page from refreshing. However, then to post the content (if there is a requirement) you will need to send that data using Ajax request.

However, if you still want to do that, then you might want to register a script to that button, that in turn (using JavaScript) prevents the page from reloading.


将控件放在更新面板中。



UpdatePanel控件简介 [ ^ ]
Put your controls inside an update panel.

Introduction to the UpdatePanel Control[^]


这篇关于如何在使用C#按钮单击事件后避免页面刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆