Accessing a dynamic variable in javascript from Server Side using c# - c#

I'm trying to access a variable in Javascript from the server side (c#). I've declared this variable as public from the server side:
public string elementSliderAppend;
and accessing in javascript using:
<%=elementSliderAppend %>
So far so good, however the variable doesn't seem to be updated after the update panel refresh in my aspx page.
The variable changes all okay in the backend but the change is not happening in Javascript.
I have placed the accessing of the variable inside the update panel so it should refresh but it doesn't.
below is the code from the aspx page
<asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick" Interval="10000">
</asp:Timer>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:Asyncpostbacktrigger controlid="Timer1"> </asp:Asyncpostbacktrigger>
</Triggers>
<ContentTemplate>
<div id="flexViewer" class="flexslider">
</div>
<script type="text/javascript">
function getImgHtml() {
return <%=elementSliderAppend %>;
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
Calling the variable from the below code (also on the aspx page)
function pageLoad(sender, args) {
$("#flexViewer").html("<ul class=slides>" + getImgHtml() + "</ul>");
flexSliderRUN();
}
NEW CODE
I've now inserted the below code inside the updatepanel above
<asp:HiddenField ID="hiddimgHtml" runat="server" />
Im setting the hidden field value from code behind using
hiddimgHtml.value= elementSliderAppend;
using the below in my javascript file to access the value
var value = $("#hiddimgHtml").val();
alert(value);
$("#flexViewer").html("<ul class=slides>" + value + "</ul>");
However on the refresh im getting a very nasty looking error
POST http://:1562/FridayViewer.aspx 500 (Internal Server Error)
ScriptResource.axd?d=xz1-gVxgQeQi9AUxmqDjtx8455SyoL-b2LZdBEiJTo8-XZn2n4ZRBb…NYDXi9xlT_-BAcGHV0ZqGBzbItBzEvsjInrEIWh3G93x0XMte0bSN00lh0&t=6119e399:6073
XHR finished loading: "http://:1562/FridayViewer.aspx". ScriptResource.axd?d=xz1-gVxgQeQi9AUxmqDjtx8455SyoL-b2LZdBEiJTo8-XZn2n4ZRBb…NYDXi9xlT_-BAcGHV0ZqGBzbItBzEvsjInrEIWh3G93x0XMte0bSN00lh0&t=6119e399:6073
Uncaught Sys.WebForms.PageRequestManagerServerErrorException: Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 500 ScriptResource.axd?d=xz1-gVxgQeQi9AUxmqDjtx8455SyoL-b2LZdBEiJTo8-XZn2n4ZRBb…RNYDXi9xlT_-BAcGHV0ZqGBzbItBzEvsjInrEIWh3G93x0XMte0bSN00lh0&t=6119e399:237

<%= %> is an equivalent of Response.Write which is not intended to work with AJAX (which what UpdatePanel is). If you need to display something in an UpdatePanel - assign it to a property of a control (it could be some standard ASP.NET Control like Label and its Text property or even a SPAN with runat="server" and its innerHTML property)

you can also use hidden field.
Steps
1) set value of hidden field
2) get the value of hidden field using java script or jQuery

Thanks for everyones answers they all help resolve the issue
Im using the hidden control and setting its value from code behind
The reason for the error on postback seemed to be the length of string that was assigned to the hidden field which caused the issues. To resolve I blanked the value in javascript before postback

Related

What is the correct way to put multiple controls inside update panel?

I have one registration form which contains 3 to 4 dropdown controls and 2 datepickers and now when dropdown controls value are selected(selectedindex change are fired)
then i dont want my page to postback.
I have use update panel to stop this behaviour of post like below:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<%--Update Panel for date picker%>
<asp:UpdatePanel ID="UpdatePanelDatepicker" runat="server">
<ContentTemplate>
<telerik:RadDatePicker ID="rdpDate1" runat="server">
</telerik:RadDatePicker>
</ContentTemplate>
</asp:UpdatePanel>
<%--Update Panel for Dropdown--%>
<asp:UpdatePanel ID="updatepaneldata" runat="server">
<ContentTemplate>
<telerik:RadComboBox ID="ddlCountry" runat="server">
</telerik:RadComboBox>
</ContentTemplate>
</asp:UpdatePanel>
</ContentTemplate>
</asp:UpdatePanel>
So i just wanted to ask that is this correct way to put multiple controls under update panels??
Subscribe to ajax event of initializeRequest on client-side. In this event we can cancel an ajax postback if we need to.
The initializeRequest method is raised before processing of the asynchronous request starts. You can use this event to cancel a postback.
In this event, we will check if an async postback is being initiated due to ddlCountry, and if yes then we cancel the ajax post back so no post back occurs.
To solve your problem just do the following : Add following JavaScript to your aspx page. In code below, the pageLoad method is automatically called by ASP.Net Framework on client-side when browser loads the page and after all scripts have been loaded as well as all client-side objects created.
JavaScript to cancel combobox post back
<script type="text/javascript">
function pageLoad()
{
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(CancelComboBoxPostback);
}
function CancelComboBoxPostback(sender, args)
{
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm.get_isInAsyncPostBack() & args.get_postBackElement().id == 'ddlCountry') {
args.set_cancel(true);
}
}
</script>
The following is only a recommendation and not a part of the solution to your specific problem: Also, I would recommend to stay away from nested update panels as this can cause unexpected results if developer is not aware of how nested update panels work. In your situation, a single update panel should suffice as in markup below instead of nested update panels that you have used in your original markup.
Markup without nested update panels
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<telerik:RadDatePicker ID="rdpDate1" runat="server">
</telerik:RadDatePicker>
<telerik:RadComboBox ID="ddlCountry" runat="server">
</telerik:RadComboBox>
</ContentTemplate>
</asp:UpdatePanel>
Honestly, the UpdatePanel I find is more trouble than it is worth.
UpdatePanel controls are a central part of Ajax functionality in
ASP.NET. They are used with the ScriptManager control to enable
partial-page rendering. Partial-page rendering reduces the need for
synchronous postbacks and complete page updates when only part of the
page has to be updated. Partial-page rendering improves the user
experience because it reduces the screen flicker that occurs during a
full-page postback and improves Web page interactivity.
I often find the controls implementation causes more problems then it is worth. So I often implement my own Ajax services, to handle such logic. You can do this the old school way, quite easy.
// Create .aspx page, to be our service.
public class ControlUpdateService
{
protected void Page_Load(object sender, EventArgs e)
{
// Use an approach to determine which control type, and model to build.
// You would build your object, then use Newtonsoft.Json, to serialize, then
// return the object, via Response.End(object).
}
}
Then your page would Ajax the data, hit the service, then build your control via the .success in the Ajax call. If you do this approach, you commit to saving your data via Ajax as well. Keep that in mind. As I was answering this question, I can't help but feel your problem actually stems from the control doing an AutoPostback. Which you can actually disable.
AutoPostBack = "false";
Telerik may be different, but the documentation should clearly indicate how to disable this feature. Which would eleminate your need for an UpdatePanel all together. Allowing you to save your data, on PostBack correctly.
Use telerik Ajaxloadingpanel except UpdatePanel this is good for your code try this Example
<telerik:RadAjaxLoadingPanel ID="rlp" runat="server" Skin="Metro">
</telerik:RadAjaxLoadingPanel>
<telerik:RadAjaxPanel runat="server" LoadingPanelID="rlp" skin="Metro">
<telerik:RadDatePicker ID="rdpDate1" runat="server">
</telerik:RadDatePicker>
<telerik:RadComboBox ID="ddlCountry" runat="server">
</telerik:RadComboBox>
</telerik:RadAjaxPanel>

Updating textbox within UpdatePanel from codebehind of another page that is in an iframe in asp.net C#

I have a web application that I'm working on. On the parent page I have a status text box within an UpdatePanel. There is an iframe on the parent page that on page load executes some codebehind function in C# that happens to take a long time. (Quite a few lines of code get executed)
I was wondering how I could call out to the parent page from within the iframes code behind and do Updates on the UpdatePanel at various times in the function.
Here is some of the html from the main page:
<asp:UpdatePanel ID="StatusPanel" ClientIDMode="Static" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ClientIDMode="Static" ID="txtStatus" runat="server" Width="99%" Enabled="False"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
And some of my c# codebehind from the iframe:
foreach (CorpLead lead in leadsPriority1)
{
UpdateStatus(lead.name);
xRMData.AssignCorpLead(agentProfiles, lead, service);
}
private void UpdateStatus(string lead)
{
if (this.Parent.FindControl("txtStatus") != null)
{
((TextBox)this.Parent.FindControl("txtStatus")).Text = lead;
((UpdatePanel)this.Parent.FindControl("StatusPanel")).Update();
}
}
Without some code examples it's just a guess for your specific problem but you can access controls on the parent page like so:
if (this.Parent.FindControl("ControlID") != null)
{
((Control)this.Parent.FindControl("ControlID")).Property = value;
}
Is this what you're looking for?
Since your IFRAME calls a function - it can call a function of the parent page (I am talking about JavaScript function). That parent function can use setInterval to programmatically "click" on a hidden LinkButton control which is set as a trigger for your UpdatePanel.
Result: UpdatePanel is refreshed at given intervals

Div onload function and embedding server code c#

I am trying to call c# properties in .aspx page, where myfunc is jquery function.
this function take parameters which i am passing through c# public properties. and I want to call this function as soon as div is rendered.previously i have done this on prerender event in ascx control. wha is exact ssyntax for below code and calling jquery function from here is valid?
<div class ="v" onload ="Javascript:myfunc('<%= this.articleID %> '
,'" +<%=this.UserID %>+"','" +<%=this.EncryptedUserID %>" +','" +<%#
this.ItemIndex %>)">
thanks
Edited
Ok If i do like this way
<div class ="v" >
<script language ="javascript" >
JGetTotalVotes(<%= this.articleid %> ,<%
this.ThisEncryptedUserID %>,<% this.ItemIndex %>,'aaa');
</script>
I do not want server side hidden fields solutions and if i use hiden field ( non server html tag) then i still need to call <%%> to fetch value from server side to hiddent field
I see you are missing single quote after the last parameter if that is not the problem.
You can use hidden fields and call the function in javascript
Add this to your page
<asp:HiddenField runat="server" ID="hdnArticleId" ClientIDMode="Static" />
<asp:HiddenField runat="server" ID="hdnUserId" ClientIDMode="Static"/>
<asp:HiddenField runat="server" ID="hdnEncryptedUserID" ClientIDMode="Static"/>
<asp:HiddenField runat="server" ID="hdnItemIndex" ClientIDMode="Static"/>
bind those hiddenfields in Page_Load event remember to add ClientIDMode="Static" to set the id as you set not a generated one by asp.net to have the ability to use them in javascript
Add To your javascritp
function YourFunction(){
var ArticleId = document.getElementById("hdnArticleId").value;
var UserId= document.getElementById("hdnUserId").value;
var EncryptedUserID= document.getElementById("hdnEncryptedUserID").value;
var ItemIndex= document.getElementById("hdnItemIndex").value;
// your code goes here
}
and don't forget to call your javascript function in page onload
Div elements don't pull in external content, so they don't have load events.
If you want to run some JS after a div element has been parsed:
<div></div>
<script> foo(); </script>

Avoiding having to go back twice after writing html with an onload=document.form.submit() to HttpContext.Current.Response

So that's a long title, here's what I'm doing: To avoid having report parameters show up in the URL I'm doing this in a button click handler in the code-behind to show the report:
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Write("<html><head></head>");
System.Web.HttpContext.Current.Response.Write("<body onload=\"document.mainform.submit(); \">");
System.Web.HttpContext.Current.Response.Write(string.Format(CultureInfo.InvariantCulture, "<form name=\"mainform\" method=\"post\" action=\"{0}\">", ReportURL));
foreach (string key in Params.Keys)
{
System.Web.HttpContext.Current.Response.Write(string.Format(CultureInfo.InvariantCulture, "<input name=\"{0}\" type=\"hidden\" value=\"{1}\">", key, Params[key]));
}
System.Web.HttpContext.Current.Response.Write("</form>");
System.Web.HttpContext.Current.Response.Write("</body></html>");
This works great, but when I go back from the report I'm taken to the page I just generated which immediately submits the form due to the onload event. I can hit back twice really quickly to go back past it but this isn't ideal.
I've tried opening a new window with JavaScript using ClientScript.RegisterStartupScript before writing the html but I don't know how (or if it's even possible) to get the HttpContext for the new window.
I wasn't able to recreate the problem using your code, so more context may help. Depending on how the rest of the page is structured, you may be able to use PostbackURL instead of a click handler:
<form id="form1" runat="server">
<asp:HiddenField runat="server" ID="Key1" Value="Value1"/>
<asp:HiddenField runat="server" ID="Key2" Value="Value2"/>
<asp:Button runat="server" ID="button"
Text="ok" PostBackUrl="ReportURL.aspx"/>
</form>
This way you don't have to worry about an extra/replaced page in the browser history.
I ended up opening a new window. I added two small javascript functions
function openNewWin() {
$('form').attr('target', '_blank');
setTimeout('resetFormTarget()', 500);
}
function resetFormTarget() {
$('form').attr('target', '');
}
Then in the linkbutton I set
OnClientClick="openNewWin();"
The OnClick still executes the code above server-side but the response is written to the new window. The setTimeout in the openNewWin function resets the form's target property so the app will still function normally after coming back to it.

HTML Select items count in asp.net

Hi I've an HTML select control in my ASP.NET page and I made it as runat = "server" and now I tried to add some list items to it dynamically. something like below code
var list = document.getElementById('<%=list1.ClientID%>');
var newListItem = document.createElement('OPTION');
newListItem.text = "Emp1";
newListItem.value = "e101";
list.add(newListItem);
<asp:Panel ID="pnlemp" runat="server"
Style="display: none;"
CssClass="modalPopup"
width="700px" Height="350px">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<select id="list1" multiple="true" name="list1" runat="server">
</select>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
and now when I try to access this from my code like list1.Items.Count it is showing 0.
Anything wrong in this?
Thanks in advance
When you modify the html in a client side script, the viewstate (which keeps track of all the controls) doesn't update . That results in that when you make a postback the new items isn't "there" .
Sometimes there's a __doPostBack() javascript which forces a postback, but I'm not sure it'll work .
For solution to this problem either add items dynamically through server side code or
dont bring server side into the picture and handle everything via javascript.
Items added via javascript will not be persisted by asp.net. further more you may recieve a "Invalid Callback or PostBack Argument" Exception for the same because it will not understand from where these listitems(options) have been added in the Select.

Categories

Resources