我在这里使用Web表单而不是MVC,而且我很难找到将OnClick绑定到新生成的按钮的方法。我将自己编码到一个角落,我的页面内容从其代码中添加了hml in string
articleHTML += "<asp:Button ID='button' type='button' OnClick='Pull_Click' class='btn btn-default btn- lg'>Pull</asp:button>";
protected void Pull_Click(object sender, EventArgs e) {
LabelTest.Text = "Works";
}
单击按钮时不会调用Pull_Cick。我猜我需要直接在模板中循环浏览我的内容?谢谢!
答案 0 :(得分:3)
添加按钮的方式不正确请检查
https://msdn.microsoft.com/en-us/library/kyt0fzt1.aspx
用于点击事件
Button btn = new Button();
btn.Text = "test";
btn.Click += btn_Click;
maindiv.Controls.Add(btn);
void btn_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
按钮调用ajax
Button btn = new Button();
btn.Text = "test";
btn.OnClientClick = "newbtn_Click()";
[WebMethod]
public static string newbtnSubmit(string name)
{
return name;
}
并在JavaScript中添加
<script>
function newbtn_Click()
{
var dataValue = { "name": "my name"};
$.ajax({
type: "POST",
url: "Default.aspx/newbtnSubmit",
data: dataValue,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
complete: function (jqXHR, status) {
alert("complete: " + status + "\n\nResponse: " + jqXHR.responseText);
}
});
}
</script>