consuming c# events in web forms NO ASP CONTROLS
How would I raise an event if my html syntax is the following:
<select runat="server" id="selection" onclick="inputCheck" />
I tried this in the code behind:
protected void inputCheck(object sender, EventArgs e) 开发者_JAVA百科 { //doesnt matter because it raised an on click. }
Exception:Microsoft JScript runtime error: 'inputCheck' is undefined
Here is an example with jQuery posting back to the server using ajax method, very clean and easy to use. Let me know if you have questions.
--HTML page
<select id="selection" name="selection" />
--Place this following code in the head tag in the html surrounded by the script tags; you must also include the latest jquery code (free download from http://www.jquery.com)
$(document).ready(function()
{
$("#selection").click(function()
{
var selectionValue = $(this).val();
$.ajax({
type: "POST",
url: "CodeBehindPage.aspx/WebMethodName",
data: "{'input':'" + selectionValue + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//return value goes here if any
}
});
}
});
//Code behind page
[System.Web.Services.WebMethod]
public static bool WebMethodName(string input)
{
try
{
//do something here with the input
return (true);
}
catch(Exception ex)
{
throw ex;
}
}
--This will post the code to the server without any postbacks, which I like. In order to test, set a break point inside of the WebMethodName function and view the input passed in. HTH
The onclick
in your first snippet runs only in javascript. To raise the event server-side, the first step is to build a javascript method for this event. From there, you have a few options:
- You can build an ajax request to call a WebMethod
- You can post the event back to the original page. Since you aren't using asp control, you will have to have code in your page_load to check the posted data for the event and raise it on your own.
精彩评论