I want to add a client-side JavaScript event handler that will fire each time a row is selected or deselected on an ASP.NET Telerik RadGrid and I need to add it from JavaScript without server-side code. How can I accomplish this?
You can achieve this by using RadAjaxManager.
ASPX:
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server"
onajaxrequest="RadAjaxManager1_AjaxRequest"></telerik:RadAjaxManager>
JS:
<script type="text/javascript">
function onclientrowclick(sender, args) {
$find("<%= RadAjaxManager1.ClientID %>").ajaxRequest();
}
</script>
C#:
protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
{
//your code
}
EDIT:
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="true" AllowMultiRowSelection="true" >
<ClientSettings Selecting-AllowRowSelect="true">
<ClientEvents OnRowSelecting="OnRowSelecting" OnRowDeselecting="OnRowDeselecting" />
</ClientSettings>
</telerik:RadGrid>
JS:
function OnRowDeselecting(sender, args) {
alert("deselect");
}
function OnRowSelecting(sender, args) {
alert("select");
}
Related
I am using ASP.NET UpdatePanel for partial postback. Somehow after the server side postback (ddl_SelectedIndexChanged), the value set by a Javascript function (lblTotal's value of 100) gets removed. Is there anyway to preserve value set by the Javascript function?
JavaScript:
<script type="text/javascript">
function calculateTotal() {
var lblTotal = document.getElementById("<%= lblTotal.ClientID%>");
lblTotal.innerHTML = "100";
}
</script>
HTML:
<asp:UpdatePanel ID="UpdateGrid" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddl" runat="server" OnTextChanged="ddl_SelectedIndexChanged" AutoPostBack="true" />
<asp:CheckBox ID="chkLevels" runat="server" onclick="calculateTotal()" />
<asp:Label ID="lblTotal" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
C# / Code Behind:
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
// Some code
}
The problem is here is that when you change data with calculateTotal in Javascript, server does not know about changes since you don't post back data to server.
So you need to trigger the postback event with __doPostBack():
Client side:
function calculateTotal() {
var lblTotal = document.getElementById("<%= lblTotal.ClientID%>");
//Calculation
var totalValue = "100";
__doPostBack('chkLevels', totalValue);
}
Page_Load on Server side :
protected void Page_Load(object sender, EventArgs e)
{
if (Request["__EVENTTARGET"] == "chkLevels")
{
var totalValue = Request["__EVENTARGUMENT"];
lblTotal.Text = totalValue;
}
}
See: how to use __doPostBack function in asp.net
This question already has an answer here:
how to use webmethod with telerik batch edit grid
(1 answer)
Closed 7 years ago.
I used telerik:RadGrid batch editing; to fill this grid I used below syntax:
function GridBind(GridID, GridData) {
var TableView = GridID.get_masterTableView();
TableView.set_dataSource(GridData); TableView.dataBind();
}
To Invoke batcheditcommand I used below syntax. It’s written under non-postback button Javascript event:
function SaveAllChanges(sender,args) {
var batchManager = $find('<%=RadGrid1.ClientID%>').get_batchEditingManager();
var tableViews = [];
tableViews.push($find('<%=RadGrid1.ClientID%>').get_masterTableView());
batchManager.saveTableChanges(tableViews);
}
But unfortunately it did not fire server event RadGrid1_BatchEditCommand, so I want to invoke Radgrid batcheditcommand from code behind in C#.net.
A quick POC that worked for me:
markup:
<telerik:RadGrid ID="RadGrid1" runat="server" OnBatchEditCommand="RadGrid1_BatchEditCommand">
<MasterTableView EditMode="Batch">
<Columns>
<telerik:GridBoundColumn DataField="first"></telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="second"></telerik:GridBoundColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
<asp:Button ID="Button1" Text="bind grid" OnClientClick="bindTheGrid(); return false;" runat="server" />
<asp:Button ID="Button2" Text="save grid" OnClientClick="SaveAllChanges(); return false;" runat="server" />
<script>
function bindTheGrid() {
var grid = $find("<%=RadGrid1.ClientID%>");
var data = [{ first: 1, second: 1 }, { first: 2, second: 2 }];
GridBind(grid, data);
}
function GridBind(GridID, GridData) {
var TableView = GridID.get_masterTableView();
TableView.set_dataSource(GridData);
TableView.dataBind();
}
function SaveAllChanges(sender, args) {
var batchManager = $find('<%=RadGrid1.ClientID%>').get_batchEditingManager();
var tableViews = [];
tableViews.push($find('<%=RadGrid1.ClientID%>').get_masterTableView());
batchManager.saveTableChanges(tableViews);
}
</script>
and server code
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
RadGrid1.DataSource="";
RadGrid1.DataBind();
}
}
protected void RadGrid1_BatchEditCommand(object sender, GridBatchEditingEventArgs e)
{
Response.Write(DateTime.Now.ToString());
}
where you would need to work a bit on the client-side binding.
Make sure you have no script errors.
In the first function, do you pass a grid object or an ID in the GridID object? If only and ID, use $find() first to get a reference.
Surely will be marked as duplicate one but after tons of question and example i couldn't solve my problem.
What i want?
Calling server side event handler in asp.net from client side java script it is not going on server side. I checked it by setting breakpoint, the page flicks but server side method is not called.
My click event on code behind is
protected void btninsert_Click(object sender, EventArgs e)
{
// my code
}
aspx file
<asp:Button ID="btninsert" runat="server" ValidationGroup="form" CssClass="btn"
OnClientClick="DoPost()" Text="Save" />
Javascript method is
function DoPost() {
function DoPost() {
var chk = document.getElementById('<%= chkstatus.ClientID %>');
if (chk.checked)
__doPostBack('<%= btninsert.ClientID %>', 'OnClick');
return true;
//return false;
}
}
I also tried this
__doPostBack('btninsert', 'OnClick'); and __doPostBack('btninsert', ''); and $('btnSubmit').trigger('click'); with no success.
What am i doing wrong?
Edit: If i uses OnClick event then it is going in the server side event irrespective of the if condition in the DoPost method.
Ahh it was simple. Thanks to all answers.
Solution:
Use OnClick attribute for server side event and OnClientclick for client event for validation.
OnClientClick javascript method will return true and false which decides whether serverside onclick event will fire or not.
Code will be somthing like this
<script type="text/javascript">
function DoPost() {
var chk = document.getElementById('<%= chkstatus.ClientID %>');
if (chk.checked) {
var c = confirm("are you sure?");
if (c == true) {
return true;
} else
{ return false; }
}
return true;
}
</script>
And the Button tag
<asp:Button ID="btninsert" runat="server" ValidationGroup="form" CssClass="btn"
OnClientClick="return DoPost();" OnClick="btninsert_Click" Text="Save" />
it can work!!
if you call __doPostBack('btninsert', ''), add below to Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if ( Request["__EVENTTARGET"] == "btninsert" ) {
btninsert_Click(sender, e);
}
}
<asp:Button ID="btninsert" runat="server" ValidationGroup="form" CssClass="btn" OnClick="btninsert_Click" OnClientClick="DoPost()" Text="Save" />
Add OnClick="btninsert_Click", because without this information, asp.net has no way know which event handler to run for the "Click" event. In case you want to control whether to post back by client side script. You can do something like this:
<asp:Button ID="btninsert" runat="server" ValidationGroup="form" CssClass="btn" OnClick="btninsert_Click" OnClientClick="return DoPost()" Text="Save" />
function DoPost() {
__doPostBack('<%= btninsert.ClientID %>', 'OnClick');
return true;
//return false;
}
Note the OnClientClick="return DoPost()"
<asp:Button ID="btninsert" runat="server" ValidationGroup="form" CssClass="btn"
OnClientClick="return DoPost();" Text="Save" />
modify your line like this
You can try Ajax, by using Webmethod. I used this in my project and it works fine! You may see the question, solutions and code here: http://www.codeproject.com/Questions/416748/How-to-Call-WebMethod-of-Csharp-from-JQuery
Use ASP link button instead of ASP BUTTON. Button control is not called from javascript because it type is submit while link button type is button.
For example i have added two asp control
<asp:LinkButton ID="lbtest" runat="server" Text="Link Button"></asp:LinkButton>
<asp:Button runat="server" ID="btnbutton" Text="Button" />
and execute the page
When we view the source of running page its look like this
<a id="lbtest" href="javascript:__doPostBack('lbtest','')">Link Button</a>
<input type="submit" name="btnbutton" value="Button" id="btnbutton" />
I have an ASP.NET page (WebForm1) that opens a modal dialog WebForm2 (via OpenForm2() js function) for some further processing. Upon closing the dialog I just update the UpdatePanel via JavaScript. Now the problem is, during this js call it doesn't block the UI.
This is only happening when I am calling the OpenForm2 js method from the server side (Button1_Click). As the UI already went into block mode, upon closing the WebForm2 it doesn't wait for the completion of partial postback (JavaScript) and unblocks the UI.
If I directly call the OpenForm2 js function in OnClientClick tag of the button (Button 2 in the sample), it works well and keeps blocking the UI till completion of postback.
I tried wrapping the partial postback js code in an add_endRequest, but in that case it keeps calling the refreshUpdatePanel() js method, hence blocking/unblocking the UI keeps going on. May this be happening due to two add_endRequest used on a page in that case?
Any assistance is highly appreciated in this regard.
NOTE: I have used jQuery blockUI for blocking the page during partial postbacks.
The code sample for the WebForm1 page is as follows. (The WebForm2 aspx page just have a button to close the dialog and a related js function).
WebForm1.aspx
<head runat="server">
<title></title>
<script src="js/jquery-1.6.1.min.js" type="text/javascript"></script>
<script src="js/jquery.blockUI.js" type="text/javascript"></script>
<script type="text/javascript">
function OpenForm2() {
var url = "WebForm2.aspx";
var width = 950;
var height = 455; // screen.availHeight - (120 + 65);
// open modal dialog
obj = window.showModalDialog(url, window, "dialogWidth:" + width + "px; dialogHeight:" + height + "px; center:yes");
// partial postback to reflect the changes made by form2
refreshUpdatePanel();
//Sys.WebForms.PageRequestManager.getInstance().add_endRequest(refreshUpdatePanel);
// ** here it doesn't wait for the completion and unblocks the UI **
}
function refreshUpdatePanel() {
//window.__doPostBack('UpdatePanel1', '1');
// a timeout/delay before a client side updatepanel postback. That compelled the UI to go in blocking again with a little screen flickering.
setTimeout('__doPostBack("<%= UpdatePanel1.ClientID %>", "1")', 0);
}
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
$.blockUI.defaults.css = {};
function InitializeRequest(sender, args) {
// Whatever you want to happen when the async callback starts
$.blockUI();
}
function EndRequest(sender, args) {
// Whatever you want to happen when async callback ends
$.unblockUI();
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnLoad="UpdatePanel1_Load">
<ContentTemplate>
<asp:Label ID="Label2" runat="server" Text=""></asp:Label><br />
<asp:Button ID="Button1" runat="server" Text="Button 1" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Button 2" OnClientClick="OpenForm2();return false;" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
WebForm1.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
// some server side processing here
System.Threading.Thread.Sleep(1000);
// then calling javascript function to open form2 as modal
ScriptManager.RegisterClientScriptBlock(UpdatePanel1, UpdatePanel1.GetType(), "Button1Click", "OpenForm2();", true);
}
protected void UpdatePanel1_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"];
if (parameter == "1")
{
System.Threading.Thread.Sleep(3000);
Label2.Text = DateTime.Now.ToString();
}
}
use
function refreshUpdatePanel() {
__doPostBack"<%= UpdatePanel1.ClientID %>", '1');
}
instead of
function refreshUpdatePanel() {
window.__doPostBack('UpdatePanel1', '1');
}
thank you
<asp:UpdatePanel ID="UpdatePanel2" runat="server"
OnLoad="UpdatePanel2_Load" UpdateMode="Conditional">
<ContentTemplate>
<script type="text/javascript">
myFunction();
</script>
<asp:Label ID="Label1" runat="server" Text="1" Width="18px"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
C#:
if(condition)
{
UpdatePanel2.Update();
}
protected void UpdatePanel2_Load(object sender, EventArgs e)
{
Label1.Text += 1;
}
the Label1's value is changing but it doesn't call myFunction(). I want to call it one more time after the some condition but not using setTimeout to auto call, some ideas?
When the UpdatePanel updates the DOM and rewrites script blocks into the DOM, they are not re-executed. You need to get on the client-side event that fires after the UpdatePanel is finished and re-execute your JS blocks:
<script type="text/javascript">
function handleEndRequest(sender, args)
{
var panel = document.getElementById(sender._postBackSettings.panelID);
var scripts = panel.getElementsByTagName('script');
for(var i=0;i<scripts.length;i++) {
eval(scripts[i].innerHTML);
}
}
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(handleEndRequest);
</script>
I have made it works by refreshing the whole page