I am using jsTree to organize pages created by users. Upon right-clicking and pressing “Rename” I want to fire a JS function that hits a function in my code behind without post back (if possible). I want it to grab whichever item’s I’m on ID and rename it in the database and update the jsTree.
Here is a sample code-behind function:
[System.Web.Services.WebMethod]
protected void RenamePage(object sender, EventArgs e)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(Global.conString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("contentPageUpdate", con))
{
cmd.Parameters.Add("@title", SqlDbType.VarChar).Value = Global.SafeSqlLiteral(txtPage.Text, 1);
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
}
con.Close();
//Update Content Page Repeater
using (SqlCommand cmd = new SqlCommand("contentPageGetAll", con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
}
Don’t think of it as jQuery hitting C# functions, but rather jQuery hitting a resource identified by a URI.
When you make an AJAX request with jQuery, you give the url of the destination and it does a standard HttpRequest for that url. This can be a page (webforms) or a controller action (MVC).
Since it looks like you’re using webforms, you could make a new page to handle this request. If you put a breakpoint in the
Page_Loadmethod you’ll see that it gets fired when you invoke the AJAX method:In the javascript for the right click you can use jQuery’s
ajaxmethod like so:In your mypage.aspx:
You can get the response that is written back by adding a few arguments to your
$.ajaxcall: