Why does my no-submit (HtmlButton) still submit?

耗尽温柔 提交于 2019-12-14 03:17:53

问题


I want to dynamically make rows, which exist all along but are at first hidden, visible.

I've tried the client-side (jQuery) route, but have had problems with that.

I would prefer going down the server-side (C#) road, and I thought I had found the way to accomplish it based on this thread and this code:

HtmlButton btnAddFoapalRow = null;
. . .       
btnAddFoapalRow = new HtmlButton();
btnAddFoapalRow.Attributes["type"] = "button";
btnAddFoapalRow.InnerHtml = "+"; 
btnAddFoapalRow.ID = "btnAddFoapalRow";
btnAddFoapalRow.ServerClick += new EventHandler(btnAddFoapalRow_Click);
this.Controls.Add(btnAddFoapalRow);

private void btnAddFoapalRow_Click(object sender, EventArgs e)
{
    try
    {
        ShowNextFoapalRow();
    }
    catch (Exception ex)
    {
        String s = String.Format("Exception occurred: {0}", ex.Message); // TODO: Log this somewhere
    }
}

//// This only works the first time, because it causes the page to be reloaded, setting foapalRowsShowing back to 2
private void ShowNextFoapalRow()
{
    switch (foapalRowsShowing)
    {
        case 2:
            foapalrow3.Visible = true;
            foapalRowsShowing = 3;
            break;
        case 3:
            foapalrow4.Visible = true;
            foapalRowsShowing = 4;
            btnAddFoapalRow.Disabled = true;
            break;
    }
}


foapalrow3 = new HtmlTableRow();
foapalrow3.ID = "foapalrow3";
foapalrow3.Visible = false;
. . .
foapalrow3 = new HtmlTableRow();
foapalrow3.ID = "foapalrow3";
foapalrow3.Visible = false;

...but no go - the first time the second row is made visible, but a subsequent mashing of the "+" HtmlButton does not make the third row visible. And stepping through the code, I see why: the page is being submitted each time I mash the button, adn thus the initial code runs again, setting the number of rows visible back to two, and always making row3 visible (never row4).

This is what it looks like after mashing the button, no matter how many times I mash the button (one more row should be added, but it never is):

Row 1, BTW, is the column caption row; row 2 is the single row that is visible by default; row3 and row4 exist, but are not visible at first.


回答1:


Try using btnAddFoapalRow.Attributes.Add("onclick", "return false;");



来源:https://stackoverflow.com/questions/30947889/why-does-my-no-submit-htmlbutton-still-submit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!