简体   繁体   中英

Why won't this work to submit a form on the click of a button?

Im trying to submit a form on the click of a button in the c# web Browser control.

[form code]

<form action="sendmessage.aspx" method="post" name="sendmessage">

[C# Code]

private void Form1_Load(object sender, EventArgs e)
{
    HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
    HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");

    IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
    element.text = "function submitForm() 
    { 
        document.getElementsByName('sendmessage')[0].value.submit(); 
    }";

    head.AppendChild(scriptEl);
}

private void button2_Click(object sender, EventArgs e)
{
    webBrowser1.Document.InvokeScript("submitForm");
}

Any help would be appreciated . Thanks

If the code in your button isn't being hit, you need to bind the handler to it. You can do this in the mark-up, in your load or in the properties window. The easiest way to do it is in your properties window. Select the button, click the little lightning bolt in the properties tab and find the click event. Select your button2_Click method and that will bind it to your button. That code should then be hit.

Just a suggestion: instead of injecting JavaScript that way, declare the script on the client and either add to the onclick in the element (ugly) or add an event listener(better). If your button is only going to fire client functionality, you dont' need to handle it at all on the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM