images are not being displayed - c#

I have done the following jquery function which is supposed to change dynamically images. The problem is that it is doing nothing as if there is no jquery function. The jquery function is being totally ignored without even enter in the function.
The coding I used is the one below;
<asp:Content ID="Content1" ContentPlaceHolderID="stylesPlaceHolder" runat="server">
<script type="text/javascript">
var index = 0;
var images = [
'child.jpg',
'girl.gif',
'sponsor.jpg'
];
$('Image1').attr('src', 'Resources/ChildrenImages/' + images[0]);
setInterval(change_image, 5000);
$(document).ready(function() {
index++;
if (index >= images.length) index = 0;
$('Image1').attr('src', 'Resources/ChildrenImages/' + images[index]);
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="contentPlaceHolder" runat="server">
<div>
<asp:Image ID="Image1" runat="server" Height="198px" Width="225px"/>
</div>
</asp:Content>
Any suggestions to what the problem could be?

The problem is that you're probably not selecting anything:
$('Image1')
should be
$('#Image1')
Please note also that there's a difference between the ID that you set and the rendered one (which is ClientID in ASP.net), so you should either use:
$('img[id$="Image1"]') //Select an image whose ID ends with 'Image1'
Or reference the ClientID property in your script.

Set the ClientIDMode property of the Image to Static, and as per the other answer the JQuery Identifier should start with a #, #Image1.

Related

MaintainScrollPositionOnPostback is not working?

I have a page with two drop down lists (ddlA and ddlB)
Once the user selects an item from ddlA, it will populate items in ddlB
I have auto post-back turned on for ddlA.
and since I wanted to maintain the scroll position, i turned on the MaintainScrollPositionOnPostBack to true like this in the page load method. :
this.MaintainScrollPositionOnPostBack = true;
But this doesn't seem to fix the issue.
Is there a workaround to fix the problem.?
-- UPDATE --
I added this js code to the page and now the problem is that the autopost back is never happening..
<script type="text/javascript">
var xPos, yPos;
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
xPos = $get('scrollDiv').scrollLeft;
yPos = $get('scrollDiv').scrollTop;
}
function EndRequestHandler(sender, args) {
$get('scrollDiv').scrollLeft = xPos;
$get('scrollDiv').scrollTop = yPos;
}
</script>
Am i adding the js code incorrectly? I found it here
Try to add this to the Page directive in your ASPX file and test it that route.
<%# Page Title="" Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" MaintainScrollPositionOnPostback="true" Inherits="_Default" %>
I couldn't get MaintainScrollPositionOnPostback to work for me no matter what I tried. Based on this answer (https://stackoverflow.com/a/27505983) and a comment underneath it, I tried the following code which worked for me. This will only work if you have an ASP.NET ScriptManager (i.e. MicrosoftAjax.js) on your page. You also need JQuery added to your page. Add the below code to your .aspx file somewhere underneath asp:ScriptManager tag.
<asp:HiddenField runat="server" ID="hfPosition" Value="" />
<script type="text/javascript">
$(function () {
var positionField = $("#<%=hfPosition.ClientID%>");
window.onscroll = function () {
var position = $(window).scrollTop();
positionField.val(position);
};
});
function pageLoad() {
var positionField = $("#<%=hfPosition.ClientID%>");
var position = parseInt(positionField.val());
if (!isNaN(position)) {
$(window).scrollTop(position);
}
};
</script>
Basically we are holding the scroll position inside the value of a hidden field called hfPosition. Whenever the page is scrolled, the value will be updated. Then when a postback happens pageLoad() will automatically be called and will get the value of hfPosition and scroll to that value.
Including the ScriptManager and JQuery, my final code snippet looked something like this:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<script src="../Scripts/jquery-3.3.1.min.js" type="text/javascript"></script>
<asp:HiddenField runat="server" ID="hfPosition" Value="" />
<script type="text/javascript">
$(function () {
var positionField = $("#<%=hfPosition.ClientID%>");
window.onscroll = function () {
var position = $(window).scrollTop();
positionField.val(position);
};
});
function pageLoad() {
var positionField = $("#<%=hfPosition.ClientID%>");
var position = parseInt(positionField.val());
if (!isNaN(position)) {
$(window).scrollTop(position);
}
};
</script>/>

SAP UI5 with ASP: Repeater Control

Does anyone know how to use an sap ui5 control with the asp:repeater control. Everytime I try to put a button, it only shows up in the first iteration of the repeater. And not in the rest of the iterations
<asp:Repeater ID="NewsFeedID" runat="server" >
<ItemTemplate>
<script type="text/javascript">
var buttonlink = CommentsPage + "?news=" + '<%# Eval("NewsFeedID") %>';
var AddComment = new sap.ui.commons.Button({
text: "Add Comment",
icon: AddCommentIcon,
lite: true,
press: function () { window.location = buttonlink; }
}).placeAt("Comments");
</script>
<div id="Comments"></div>
</td>
</tr>
When I use this code it only shows up for the first iteration of the asp:repeater but I want it to show up for all iterations. Does it have something to do with the div id=Comments? Need help please
Your Repeater creates multiple <div> elements with the same id, which causes conflicts.
One way to fix the problem is to add a runat="server" attribute to the <div>, making it a server-side control so that ASP.NET generates a unique ID for each instance:
<div runat="server" id="Comments"></div>
Then pass the dynamically generated ID to the placeAt function:
}).placeAt("<%# Container.FindControl("Comments").ClientID %>");
You can rename every instance with the index of repeater item:
<script type="text/javascript">
var buttonlink = CommentsPage + "?news=" + '<%# Eval("NewsFeedID") %>';
var AddComment = new sap.ui.commons.Button({
text: "Add Comment",
icon: AddCommentIcon,
lite: true,
press: function () { window.location = buttonlink; }
}).placeAt("<%# "Comments"+ Container.ItemIndex+1 %>");
</script>
<div id="<%# "Comments"+ Container.ItemIndex+1 %>"></div>

Unable to make AJAX code work

Just getting started with AJAX and tried a simple example in the microsoft 70515 book. However, the code doesnt seem to work, and I can't figure out why not - as it seems ok.
Edit: for some reason a part of the code did not get posted, (even as I am writing this now the code looks weird, it is like I can't post all my code??) I've fixad that now- but what's up with the down vote? I cant really see what is stupid about my question. Please explain.
Hoping somebody can spot the problem and help me out here :)
Markup .aspx:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="AjasxTest._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager>
<br /><br />
<script type="text/javascript">
function ClientCallbackFunction(args) {
window.LabelMessage.innerText = args;
}
</script>
</asp:Content>
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="FooterContent">
<asp:DropDownList ID="DropDownListChoice" runat="server" OnChange="MyServerCall(DropDownListChoice.value)">
<asp:ListItem>Choice 1</asp:ListItem>
<asp:ListItem>Choice 2</asp:ListItem>
<asp:ListItem>Choice 3</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="LabelMessage" runat="server"></asp:Label>
</asp:Content>
Code-behind:
namespace AjasxTest
{
public partial class _Default : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
string callbackRef = Page.ClientScript.GetCallbackEventReference(this, "args", "ClientCallbackFunction", "");
string callbackScript = String.Format("function MyServerCall(args) {{{0};}}", callbackRef);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"MyServerCall", callbackScript, true);
}
public string GetCallbackResult()
{
return _callbackArgs;
}
string _callbackArgs;
public void RaiseCallbackEvent(string eventArgument)
{
_callbackArgs = eventArgument;
}
}
}
Your JS function is called ClientCallbackFunction but you're calling it in the DropDownList OnChange event as MyServerCall.
<script type="text/javascript">
function ClientCallbackFunction(args) {
window.LabelMessage.innerText = args;
}
</script>
...
<!-- Call correct JS function in OnChange -->
<asp:DropDownList ID="DropDownListChoice" runat="server" OnChange="ClientCallbackFunction(DropDownListChoice.value)">
...
Your code is pretty close, however the problem is in the fact you are trying to access ServerSide objects (such as Label and DropDownList) from the client side.
For example, an asp:Label control, when rendered to a web browser on the client side, is actually an HTML div. The ID of the label in Visual Studio might be "LabelMessage", but depending on the layout of your page and controls, the ID on the client side (i.e., for the user that clicks view source in FireFox or IE) could be generated as "FooterContent_LabelMessage1" or something like that.
ASP.net controls do come with a property you can use to access the generated ID in JavaScript, which can be accessed by YourControl.ClientID.
I've made these changes to your code and have been able to make it work. I also added some null reference checking in the JavaScript to ensure the objects we are trying to reference, in fact, exist. Note I've tested this in a blank, brand new ASP.net forms application.
Here's the updated code for the Default page (front end):
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="TheAnswer._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<br />
<br />
<script type="text/javascript">
function ClientCallbackFunction(args) {
var labelMessage = $get("<%= LabelMessage.ClientID %>");
if (labelMessage) {
labelMessage.innerText = args;
}
}
function MyServerCallWrapper() {
var dropDown = $get("<%= DropDownListChoice.ClientID %>");
if (dropDown) {
MyServerCall(dropDown.value);
}
}
</script>
</asp:Content>
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="FooterContent">
<asp:DropDownList ID="DropDownListChoice" runat="server" onchange="javascript:MyServerCallWrapper();">
<asp:ListItem>Choice 1</asp:ListItem>
<asp:ListItem>Choice 2</asp:ListItem>
<asp:ListItem>Choice 3</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="LabelMessage" runat="server"></asp:Label>
</asp:Content>
Note the $get() function is a built-in ASP.net (not JQuery) function that is shorthand for document.getElementById() - they are interchangeable and do exactly the same thing. You need to pass the ClientID in quotes to either of these methods in JavaScript, and it will return a reference to the object you are trying to access.
Just for fun, I modified one of the back-end functions so you know that the call back was processed on the server:
public string GetCallbackResult()
{
return _callbackArgs + " from the server!";
}
And voila! this works for me -
I hope it works for you too and I hope it's clear where the problem was; most of your example was working / setup perfectly.

The Controls collection cannot be modified because the control contains code blocks

This is a bit different to all the other questions as they all seem to refer to the head content specifically. With this one, I have a user control with the following placeholder:
<asp:PlaceHolder runat="server" ID="DiscussIncludes">
<script>
var OnLastPage = <asp:Literal runat="server" ID="OnLastPageJS" />;
var AJAXWait = false;
var MinChars = <%=Settings.MinimumCommentChars%>;
var AJAXURL = "<%=ResolveClientUrl("~/Handlers/DiscussAjaxHandler.ashx")%>";
var CurrUsername = "<%=ThisUser.Username %>";
var GravHash = "<asp:Literal runat="server" ID="GravJSRef" />";
var RelURL = "<%=ResolveClientUrl("~/users/")%>";
var Anch = "<%=Anchor.ToString()%>";
var MyRep = "<%=MyRepString%>";
var CurrReportID = 0;
var LastPageURL = "<asp:Literal runat="server" ID="JSLastPageURL" />";
var AllowedChars = <%=Settings.MaxCommentChars %>;
</script>
<script src="<%=CommonFunctions.AllocateStaticPath("/js/Discuss.js?v=" + Settings.JSVersionID)%>"></script>
<script src="<%=CommonFunctions.AllocateStaticPath("/js/BlockUI.js?v=" + Settings.JSVersionID)%>"></script>
</asp:PlaceHolder>
In the code behind I have:
ContentPlaceHolder FooterControl = (ContentPlaceHolder)Page.Master.FindControl("JavascriptIncludes");
FooterControl.Controls.Add(DiscussIncludes);
This throws the error:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
On the FooterControl.Controls.Add(DiscussIncludes); line. I've tried changing all the <%= to <%# within the placeholder but no luck.
One point to note is this control works fine on all my other pages. Any ideas what would be causing this?
Nothing in this control is causing the problem -- if it happens when you add the control to a particular environment and only that environment the that points at the issue. What is going on on the complaining page?
I tried the following on my system and it seems to be working...
<asp:PlaceHolder runat="server" ID="DiscussIncludes">
<script type="text/javascript">
var path = <%=Common.path%>;
</script>
<script type="text/javascript" src='<%=Common.GetScriptPath("jquery-1.4.1-vsdoc.js")%>'></script>
<asp:PlaceHolder runat="server" ID="JsIncludes">
</asp:PlaceHolder>
</asp:PlaceHolder>
on code behind..
LiteralControl include = new LiteralControl(string.Format("<script src='{0}'></script>", Common.GetScriptPath("jquery-1.4.1.min.js")));
JsIncludes.Controls.Add(include);
I get the exception if i try to add the control to DiscussIncludes. However if add the control to JsIncludes it works. JsIncludes control is a child placeholder of DiscussIncludes.

Passing value from code-behind to Javascript

I am using a jQueryUI ProgressBar to show users how much allowed file storage they have used. The percentage is calculated in code-behind and should be passed to Javascript.
Aspx Code
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<script type="text/javascript">
$(function () {
var pct = document.getElementById("filesPercentage").value;
$("#progressbar").progressbar({
value: pct
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
...
<input type="hidden" runat="server" id="filesPercentage" />
<div id="progressbar"></div>
...
</asp:Content>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
filesPercentage.Value = "85";
}
It seems like it can't get the percentage number from the hidden field. Any help would be appreciated.
You need to get the rendered id of your hidden input
var pct = document.getElementById("<%=filesPercentage.ClientID%>").value;
and from the moment that you run the input on server its better to use the asp:HiddenField and not the input
since your hidden field is a server control it could be that the ID is getting generated to something other than filesPercentage (probably something like ctl00_ctl00_filesPercentage)
You may need to apply the generated client ID to your javascript document.getElementById("<%=filesPercentage.ClientID%>").value;
Or use another way of selecting the hidden value, such as $('[hidden's parent element] input[type="hidden"]').val()
additionally, it looks like progressbar value is expecting a number, so you may need to do value: pct * 1 or value: parseInt(pct)
http://jsfiddle.net/pxfunc/QyZSs/
Try this
var pct = document.getElementById("<%=filesPercentage.ClientID %>").value;
.net will modify the id you give a control to ensure it is unique, so you are not accessing it with the correct id. If you give the hidden field a unique class name, you can access the value that way:
<input type="hidden" runat="server" id="filesPercentage" class="hiddenClass" />
var pct = $('.hiddenClass').val();
This is a bit cleaner IMHO :-)
$("#progressbar").progressbar({
value: $("#<%=filesPercentage.ClientID%>").val()
});

Categories

Resources