c# asp UpdatePanel.Update() not working with jQuery's get - javascript

Got a simple test case and not sure why the code is not behaving the same way when calling the url using jQuery's get method.
Code behind:
protected UpdatePanel UpdPanel;
protected PlaceHolder PlHolder;
protected virtual void Page_Load(object sender, EventArgs e)
{
PlHolder.Controls.Clear();
var count = Request.QueryString["count"];
AddControl(string.IsNullOrEmpty(count) ? 10 : Convert.ToInt32(count));
}
public void AddControl(int count)
{
for (var i = 0; i < count; i++)
{
var control = (TestList)Page.LoadControl("~/List/TestList.ascx");
control.TextBoxText = string.Format("{0} - test", i);
PlHolder.Controls.Add(control);
}
UpdPanel.Update();
}
Markup:
<asp:UpdatePanel runat="server" ID="UpdPanel" UpdateMode="Conditional">
<ContentTemplate>
<asp:PlaceHolder runat="server" ID="PlHolder"></asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
Javascript:
<script type="text/javascript">
$(function() {
var link = $('.link'),
url = window.location.href.replace("#", "") + "default.aspx?count=20";
link.on('click', function() {
$.get(url);
});
});
</script>
If I use url http://localhost:54645/default?count=20 directly in browser the UpdatePanel.Update() is working fine, but using the jQuery's get it doesn't do anything.
The page life cycle events are triggered in a same way and there are no differences (at least I think so).
Also tried using $.post() with no change.
Any help appreciated.

you need to put an asp:button INSIDE the panel.
UpdatePanel actually do a full post-back, and the page in the client knows to update the relevant part, so you need to keep this in mind in you Page_Load method.

Related

OnServerClick with dynamic anchorlink not firing

I'm trying to fire an OnServerClick event from some anchor tag created dynamically. My event isn't firing from my anchor tag. i have no error.
Can someone help me ?
HtmlAnchor btn_close = new HtmlAnchor();
btn_close.Attributes.Add("class", "close");
btn_close.Attributes.Add("data-dismiss", "alert");
btn_close.Attributes.Add("aria-label", "Ne plus afficher");
btn_close.Attributes.Add("title", "Ne plus afficher");
btn_close.Attributes.Add("runat", "server");
btn_close.ServerClick += new EventHandler(hideNotificationBtn_Click);
btn_close.ID = notificationSent.NotificationSentID.ToString();
btn_close.InnerText = "test";
div_alert.Controls.Add(btn_close);
protected void hideNotificationBtn_Click(object sender, EventArgs e)
{
HtmlAnchor cb = (HtmlAnchor)sender;
int test = int.Parse(cb.Name);
NotificationSent.SetNotificationAsHidden(int.Parse(cb.Name));
}
My hide notification isn't fired from by anchor when i click on it.
I already tried to change it to a button.
Thank you for your help.
Anchors don't call server side functions even when they are runat server, however there is the LinkButton class that can be used instead. Ultimately it is rendered as JavaScript initiated postback. Check out https://forums.asp.net/p/1519048/3644158.aspx for more information.
Make sure you are creating that button early enough in the page lifecycle. Look to get it created OnInit of the Page.
This is because the event handling events happen after Page Init. Of course, the button has to have been created before the events can be detected on
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["falg"] != null)
{
Create();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Create();
ViewState.Add("falg", true);
}
void BtnServices_Click(object sender, EventArgs e)
{
Response.Write("hi");
}
void BtnServices_Command(object sender, CommandEventArgs e)
{
Response.Write("hi");
}
void Create()
{
BtnServices = new Button();
BtnServices.ID = "BtnServices";
BtnServices.Text = "Click Me";
BtnServices.Click += new EventHandler(BtnServices_Click);
BtnServices.Command += new CommandEventHandler(BtnServices_Command);
form1.Controls.Add(BtnServices);
}
Easier and reliable way to do this could be , instead of dynamically
adding the control, always add it, but set Visible=false initially.
Then where you're currently adding it, instead just make it visible.

how to bind the Data to Listbox asynchronously in asp.net?

Currently I'm have around 2000 building data which is being loading in the listbox due to which the page loads slowly and I want load only i.e 10 building on page load so that page could load faster and other UI control could load faster.
tried:
For this I've added the result of grid in session so when the user clicks on the particular link in grid it does not hit the SP/database and get result from session but it does not help much.page
loading still is slow
So is there any other way to load the Listbox faster ?
adding the code
code .aspx
<asp:ListBox ID="drpBuilding" runat="server" CssClass="formcontrol"SelectionMode="Multiple"></asp:ListBox>
c# code
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack) {
this.drpBuilding.Items.Clear();
List<PResponse.BLL.Building> lstBuildings = default(List<PResponse.BLL.Building>);
if (Session["buildinglist"] == null) {
lstBuildings = this.mBuildingBLL.Get_ContactSiteBuildingsListLoad(p_ContactID: UserWrapper.GetCurrentUser().ContactID, p_ShowInactive: false);//SP method
Session["buildinglist"] = lstBuildings;
} else {
lstBuildings = Session["buildinglist"]; //not hitting the SP/DB getting value from SP
}
if (lstBuildings.Count > 0) {
this.drpBuilding.Enabled = true;
this.drpBuilding.DataSource = lstBuildings;
} else {
this.drpBuilding.Enabled = false;
}
this.drpBuilding.DataTextField = "Building";
this.drpBuilding.DataValueField = "BuildingID";
this.drpBuilding.DataBind();
}
}

Dynamically added button omits confirm

I'm developing a website for users where I add controls dynamically.
The problem is that after a confirmBox appears it doesn't matter what I click (Ok/Cancel) it still deletes my objects.
This is how I add them from codeBehind:
aPanel.RegisterAction("DeleteStuff", "Delete object",
true, btnDeleteClick, null);
where aPanel is ActionPanelDx
right after this comes:
if (actionPanel["DeleteStuff"] != null)
actionPanel["DeleteStuff"].ClientSideEvents.ItemClick =
"function(s,e){return confirm('Are you sure you want to delete?')}";
protected void btnDelete_Click(object sender, MenuItemEventArgs e)
{
//Im using self written classes for handlig SQL logic it looks like this:
MySQLCommand commad = new MySQLCommand("delete_object");//procedure
commad.MyParam.AddWithValue("#ob_id", ObjectID);
commad.myExecuteNonQuery();
}
Am I using the JS function in a wrong?
Now what your code does it to delete your object whenever a button (doesn't matter which) is clicked. What you need to do is something like that:
protected void btnDelete_Click(object sender, MenuItemEventArgs e)
{
if (e.item.name === "Yes")
{
MySQLCommand commad = new MySQLCommand("delete_object");//procedure
commad.MyParam.AddWithValue("#ob_id", ObjectID);
commad.myExecuteNonQuery();
}
}
instead of e.item.name it could be e.item.text or something like that, put a breakpoint or console.log to see what is inside of your e property if you not sure.

Dynamically open a radwindow defined in Javascript

Objective:- From the server-side, I need to open a radwindow(defined in JavaScript of the aspx page) automatically on an IF condition.
Code used:-
In aspx page, I defined the radwindow as:-
<telerik:RadWindowManager Skin="WBDA" ID="AssetPreviewManager" Modal="true"
EnableEmbeddedSkins="false" runat="server" DestroyOnClose="true" Behavior="Close"
style="z-index:8000">
<Windows>
<telerik:RadWindow ID="DisclaimerAlertWindow" runat="server" Width="720px" Height="220px"
Modal="true" visibleStatusbar="false" VisibleTitlebar="false" keepInScreenBounds="true" title="Sourav">
</telerik:RadWindow>
</Windows>
</telerik:RadWindowManager>
In JavaScript, a function is defined for opening the radwindow:-
function openRadWindow()
{
var oWnd = radopen('DisclaimerAlert.aspx, 'DisclaimerAlertWindow');
oWnd.set_title('Access Denied !');
oWnd.Center();
return false;
}
So on the server side of the aspx page, In the Page Load event an IF condition is checked and then I'm calling 'openRadWindow()' function as:-
protected void Page_Load(object sender, EventArgs e)
{
if (fieldValue == "False")
{
string xyz = "<script type='text/javascript' lang='Javascript'>openRadWindow();</script>";
ClientScript.RegisterStartupScript(this.GetType(), "Window", xyz);
}
}
Problem:-
But on running this, these JavaScript errors are coming:-
Object doesn't support this property or method.
'undefined' is null or not an object
Please help how to achieve my objective. I am totally stuck.
Hi I want to share with you my solution to create RadWindow dialog in Javascript code only.
We need to implement 2 methods: one for initializing RadWindow dialog, and the last one for recieving the arguments returned after closing the RadWindow. You can do what you want in this second step (e.x postback,...)
Here is my code:
Initializing RadWindow dialog:
function openMyDialog(url, args) {
var manageWindow = GetRadWindowManager();
if (manageWindow) {
var radWindow = manageWindow.open(url, "<your_dialog_name>");
if (radWindow) {
radWindow.set_initialBehaviors(Telerik.Web.UI.WindowBehaviors.None);
radWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.Move + Telerik.Web.UI.WindowBehaviors.Close + Telerik.Web.UI.WindowBehaviors.Resize);
radWindow.setActive(true);
radWindow.SetModal(true);
radWindow.center();
radWindow.set_visibleStatusbar(false);
radWindow.set_keepInScreenBounds(true);
radWindow.set_minWidth(640);
radWindow.set_minHeight(480);
radWindow.setSize(640, 480);
radWindow.set_destroyOnClose(true);
radWindow.add_close(closeMyDialog);//after closing the RadWindow, closeMyDialog will be called
radWindow.argument = args;//you can pass the value from parent page to RadWindow dialog as this line
}
}
}
Closing the RadWindow dialog:
function closeMoveProjectDialog(sender, args) {
var objArgs = args.get_argument();
//objArgs variable stored the values returned from the RadWindow
//you can use it for your purpose
}
How to call this?
You can put the open method into your expected method. In my side, I have a method as shown below and I will call the RadWindow as this way:
function ShowForeignKeyFrontEditSingle(param1, param2){
var url = "ForeignKeyFrontEditSingle.aspx";
var objArgs = new Array();
objArgs[0] = param1;
objArgs[1] = param2;
openMyDialog(url, objArgs);
return;
}
Of course, you have to declare a RadWindowManager control
function GetRadWindowManager() {
return $find("<%=your_radwindow_manager_control.ClientID%>");
}
Take a look here, it explains how to use the ScriptManager.RegisterStartupScript method: http://www.telerik.com/help/aspnet-ajax/window-troubleshooting-javascript-from-server-side.html. Note it the ScriptManager's method. Also look at the Sys.Application.Load event to prevent your code from executing too early.

Closing RadWindow using RadButton

I'm trying to use a RadButton to close a radwindow from with the window itself (via javascript). Is it possible to call a script to close the window? Here is the javascript:
function getRadWindow()
{
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow;
else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
return oWindow;
}
function closeWindow()
{
getRadWindow().close();
}
And here is the button:
<telerik:RadButton ID="CancelButton" runat="server" OnClick="closeWindow();" CssClass="clicker" Text="Cancel" UseSubmitBehavior="False" EnableEmbeddedScripts="false" CausesValidation="False" RegisterWithScriptManager="False">
</telerik:RadButton>
I have tried everything, the script will only work if I use a pure HTML element such as an anchor tag. If I use the OnClick event I get the following error when the window opens: Compiler Error Message: CS1026: ) expected.
Am I missing something?
Thanks!
I'm not sure if I am improving this answer, I'm just trying to make it easier to understand. I have a rad window that is opened from a main page. The radwindow is opened in Code Behind (C#), not Javascript. When my user clicks a Save button on the RadWindow, it performs some logic tasks, then it closes the radwindow itself. You simply need to:
Put thise code block in you RadWindow aspx.....
<telerik:RadCodeBlock runat="server" ID="rcb1">
<script language="javascript" type="text/javascript">
function GetRadWindow()
{
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow;
else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
return oWindow;
}
function CloseDialog(button)
{
GetRadWindow().close();
}
</script>
</telerik:RadCodeBlock>
Put this code in your RadWindow's button click after you perform your pre-close logic (the same button that performs the other logic closes the window)
C#
ClientScript.RegisterStartupScript(typeof(string), "", "CloseDialog();");
OR
VB
ClientScript.RegisterStartupScript(Me.GetType(), "", "CloseDialog();")
If you're wondering how to open the radwindow from codebehind here is how I did it:
RadWindow window1 = new RadWindow();
// Set the window properties
window1.NavigateUrl = "winStrengthChart.aspx?EMPLOYIDNAME=" + parmString;
window1.ID = "RadWindow1";
window1.Width = 800;
window1.Height = 650;
window1.VisibleStatusbar = false;
window1.Behaviors = Telerik.Web.UI.WindowBehaviors.Close | Telerik.Web.UI.WindowBehaviors.Resize | Telerik.Web.UI.WindowBehaviors.Move;
window1.VisibleOnPageLoad = true; // Set this property to True for showing window from code
rwm1.Windows.Add(window1);
this.Form1.Controls.Add(window1);
...AND of course you need a basic RadWindowManager on the main page that opens the window:
<telerik:RadWindowManager ID="rwm1" runat="server">
<Windows>
</Windows>
</telerik:RadWindowManager>
This should work if I have made a mistake please correct me.
Thanks
The way to call a function from the RadButton is by using either its OnClientClicked or OnClientClicking event. Then you need to pass only the name of the JavaScript function, without parenthese. OnClick is a property for the server handler, this is also the case with the regular asp button. Try this:
<telerik:RadButton ID="CancelButton" runat="server" OnClientClicked="closeWindow" AutoPostBack="false" CssClass="clicker" Text="Cancel" UseSubmitBehavior="False" EnableEmbeddedScripts="false" CausesValidation="False" RegisterWithScriptManager="False">
Note the AutoPostBack property is set to false to prevent the postback.

Categories