In my WebApplication I have some code like this.
$('.form-content').append('<ul>' +
'<li runat="server" OnClick="SelectUser" value="1">User 1</li>' +
'<li runat="server" OnClick="SelectUser" value="2">User 2</li>' +
'<li runat="server" OnClick="SelectUser" value="3">User 3</li>' +
'</ul>');
But, when I select the list item, the Event doesn't trigger. Is there any way to bind ASP.NET event to html control which is dynamically generated by JQuery/Javascript ?
I tried using WebMethod. But, It cannot update the ASP.Net controls since the method is static.
If all else fails you can try this, add hidden asp:button
on your page and make sure that you have an onclick event attached to it.
<asp:Button ID="btnSelectUser" runat="server" Text="" OnClick="btnSelectUser_OnClick" />
then in your javascript add click events to your li
$("li").click(function() {
$("#btnSelectUser").trigger("click")
});
that should fire the serverside event.
The other thing that you will need to keep in mind is that you will need to place hidden labels
on the page to save the selected values of the li
$("li").click(function () {
$("#hiddenLabel").val("Get value from attr")
$("#btnSelectUser").trigger("click")
});
then those values should also be available on the server.
This is by now means the best why to-do it, but it will work.
I have made a fiddle similar to your requirement.
$(document).ready(function () {
$("#btnSubmit").on("click", function () {
debugger
addList();
return false;
});
function addList() {
$('.form-content').append('<ul>' +
'<li runat="server" value="1">User 1</li>' +
'<li runat="server" value="2">User 2</li>' +
'<li runat="server" value="3">User 3</li>' +
'</ul>');
}
$(".form-content").on("click", "li", function () {
SelectUser($(this));
});
function SelectUser(obj) {
alert("User Selected!");
$.ajax({
type: "POST",
url: "./YourPage.aspx/SelectUser",
data: ("ID=" + $(obj).prop("id")),
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
success: function (result) {
alert("success");
}
});
return false;
}
});
You can do anything inside SelectUser()
. Even Invoke the Serverside event
.
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.