Dynamically set picture src asp.net - asp.net

is it possible to set the src of a image with a button click.
Each of my buttons represents a picture that should be displaying in my "image" area. I need the image Area's SRC property to be affected by the button click.
Im using visual studio 2012 with c#.
-Edit : Using AJAX Update panel in visual studio 2012 with C#

If a postback is acceptable to you for every image change, you may do something like :
In C#:
protected void btnClick(object sender, EventArgs e) {
Button btn = (Button) sender;
switch (btn.ID) {
case "btn1": img.ImageUrl = "<Image_Url>"; break;
case "btn2": img.ImageUrl = "<Image_Url>"; break;
}
}
In ASPX Page:
<asp:Image ID="img" runat="server" />
<asp:Button ID="btn1" runat="server" OnClick="btnClick" />
<asp:Button ID="btn2" runat="server" OnClick="btnClick" />

Yes. You will be able to accomplish this by using JavaScript and attaching a click handler to the button (onclick="loadImage1()").
loadImage1 function would require you to write the javascript necessary to access the src attribute of the image element and alter it.
You can achieve this with plain javascript (see above concept), or with some javascript library such as jQuery. For cross browser compatibility and to save you from having to write your cross browser safe logic, I would suggest jQuery to handle this.
<img id="img1" src="initialimagehere.jpg"/>
And then you can change the src attribute like this:
$("#img1").attr("src","newimagehere.jpg");
jQuery: this link

I noticed if I had not first specified a value for ImageUrl in my .aspx code, I could not then set it in the .aspx.cs code.
Ie, if I had my .aspx code as:
<asp:Image runat="server" id="imgPickLg0101" class="ImgSzLarge" />
I could not set it in the code behind.
However, if I first specified a value for ImageUrl:
<asp:Image runat="server" id="imgPickLg0101" class="ImgSzLarge" ImageUrl="../Images/somepic.jpg" />
Then I could set it in the .aspx.cs code:
imgPickLg0101.ImageUrl = "../Images/DifferentPicture.jpg";

Inside aspx:
<img id="imagenCabecera" runat="server" />
And inside aspx.vb:
imagenCabecera.Attributes("src") = "url-image.jpg"

Related

asp.net imagebutton new window

I have a Telerik Grid. In that I have the following code in an .aspx page. What I want to happen is that when the user click on the imagebutton control it launches a new window to show that image. Note, I have seen some code which use Postback but they are blocked by popup blockers. The control's image is set via codebehind but that should not matter for this question. Here is my code. Thanks!
<asp:ImageButton ID="prod_image_main" runat="server" AlternateText="Product Main Image"
Height="500PX" Width="540PX" />
Instead of using an asp:ImageButton control why not just use a link? That way you can simply set the target attribute of the link to _blank and have it open in a new window.
Something like this:
<img src="wherevertheimageis.jpg" />
Try to open a new window with a javascript function:
function OpenW() {
window.open('NewForm.aspx', '', "height=200,width=200");
}
And in your imageButton set the onclientclick:
<asp:ImageButton ID="prod_image_main" runat="server" AlternateText="Product Main Image"
Height="500PX" Width="540PX" onclientclick="OpenW()" />
And load the image at the onload of NewForm.
Based on Mike Evan's answer here is what works for me.
ASPX FILE:
<asp:HyperLink runat="server" ID="hpl_mainimg" Target="_blank">
<asp:Image ID="prod_image_main" runat="server" AlternateText="Product Main Image"
Height="500PX" Width="540PX" /> </asp:HyperLink>
Code Behind C#
prod_image_main.ImageUrl = File.Exists(Server.MapPath("images_products/" + rdr["image_1"].ToString())) ? "images_products/" + rdr["image_1"].ToString() : "images_missing/NotAvailable_RS.jpg";
prod_image_main.ToolTip = rdr["itemtitle"].ToString();
hpl_mainimg.NavigateUrl = prod_image_main.ImageUrl.ToString();

how to use image button to open the url in another window

Hi I know how to acheive this in hyperlink by setting target = _blank , how can i do this using image button control , below is my code:
<asp:ImageButton OnClick="test_Click" ImageUrl="/images/contactUs/directionbtn.png" ID="test" runat="server" ValidationGroup="group2" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="txtPostcode1" ErrorMessage="Postcode is required" ValidationGroup="group2"></asp:RequiredFieldValidator>
<br />
Code behind:
protected void test_Click(object sender, ImageClickEventArgs e)
{
Response.Redirect(String.Format("http://maps.google.co.uk/maps?saddr={0}&daddr=&daddr=Wigan+WN6+0HS,+United+Kingdom&iwloc=1&dq=Tangent+Design", txtPostcode1.Text));
}
Any help or advice will be highly appreciated
protected void Page_Load() {
ControlID.Attributes.Add("target", "_blank");
}
If that doesn't work, try adding this to your ImageButton:
<asp:ImageButton runat="server" OnClientClick="window.open('http://url/to/open');" ></asp:ImageButton>
I just figure it out..
On Page_Load event, put
this.Form.Target = "_blank"; // Will set all link's target to a new window
Then for example in a image button Click event, you put:
Response.Redirect("http://stackoverflow.com");
It will simply open this page in a new tab. Try it :)
you could use the Attributes collection to add "target","_blank"
this should add the target attribute to the anchor link surrounding the image
Add target="_blank" to onClientClick will do the trick
In the code behind.
imgbtn.OnClientClick = "target='blank'";
And you're done.
Try this:
<asp:ImageButton OnClick="test_Click" ImageUrl="/images/contactUs/directionbtn.png" ID="test" runat="server" ValidationGroup="group2" OnClientClick="form1.target ='_blank';" />
this.Form.Target = "_blank";
This way the client can see what he wants in a new page, since the server and what is available and his account in the site available at the beginning PageLoad

How to display an image in a new window

I have a follow-on question to How to display an image based on SelectedValue in a GridView?
What I would really like to do is have a ViewImage button on my GridView control so that when that is clicked, the image is displayed on a new page in a new browser window. How would I do that? I'm thinking perhaps do I need to create a
<asp:ButtonField>
How do I handle the click and how do I get the image to diplay on a new form in a new web browser window?
Thanks very much for looking.
You can use TemplateColumn, in that TemplateColumn you can define a button where you put javascript function to open new window.
Example:
<asp:TemplateField>
<ItemTemplate>
<input type="button" onclick="javascript:ShowImageInNewPage('PageToShowImage.aspx?tradeId=<%# Eval("TradeId") %>');" />
</ItemTemplate>
</asp:TemplateField>
The "ShowImageInNewPage" function is a custom function you declare to popup/open new window with the selected image url.
In PageToShowImage.aspx, declare an img tag:
<asp:Image ID="imgBlah" runat="server" />
In code behind of PageToShowImage.aspx:
protected void Page_Load(object sender, EventArgs e)
{
// this is querystring from GridView page
if(Request.QueryString["tradeId"] != null)
{
imgBlah.Src = "GetImage.aspx?entityId=" + tradeId + "&entityType=T";
}
else
{
imgBlah.Src = "~/images/no-image.jpg"; // set no image
}
}
HTH
I'm hoping that you're dealing with browser supported image formats. Assuming you are, you don't need a ButtonField. One approach would be to use an <asp:HyperLink> in a TemplateColumn, as Arief suggested.
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="hyperLink1" runat="server" NavigatUrl="UrlToYourViewImagePage" Text="View Image" />
</ItemTemplate>
</asp:TemplateField>
If you want the image to open in a new window, build a window.open call for each HyperLink's NavigateUrl.

ASP.NET Repeater question

I have a repeater control and under the ItemTemplate, I have Image control. Anyway the old
How can I set the ImageUrl programatically?
Anyway, the old html code I have was like this:
<ItemTemplate>
<img src="<%# Eval("ImageSource") %>" alt="" />
</ItemTemplate>
But I want to check if the image exists in directory or not then I can setup with temp image.
I have a code but .. it's not really working so there's no sense of showing it here. Can you guys help me? Should I use ItemCreated or ItemDataBound event?
In the xml side in the template, you need to call a method directly.
<asp:Image runat="server" ID="myImg" ImageUrl='<%# MyImageUrlFunction(Eval("DataFieldName").ToString()); %>' />
You need a corresponding method in the code behind defined publicly:
public string MyImageUrlFunction(string field)
{
// put some logic here to determine url
return imageUrl;
}
In your ItemDataBound, do something like:
protected void rpt_ItemDataBound(object sender, RepeaterEventArgs e)
{
HtmlImage img = (HtmlImage)e.Item.FindControl("img");
string imageUrl = (string)DataBinder.Eval(e.Item.DataItem, "ImageSource");
if (File.Exists(imageUrl))
img.Src = imageUrl;
}
That's System.Web.UI.HtmlControls.HtmlImage, System.Web.UI.DataBinder and System.IO.File.
ItemDataBound. You can get the control reference through the current item's findcontrol event, and then check to see that the image exists. You can get the file path using Server.MapPath("~/images/test.png"), and then if it doesn't, inject your own.
You can also use a public method that the client-side markup can call, pass in the URL, and provide a default if it doesn't exist.
HTH.
<ItemTemplate>
<asp:Image ImageUrl='<%# System.IO.File.Exists(Eval("ImageSourceProperty").ToString()) ? Eval("ImageSourceProperty").ToString() : TemporaryImagePath %>' runat="server" />
</ItemTemplate>
for the Error
The server tag is not well formed
You should remove extra space in your code!
<%# System.IO.File......%>
should be <%#System.IO.File......%>

OnClick vs OnClientClick for an asp:CheckBox?

Does anyone know why a client-side javascript handler for asp:CheckBox needs to be an OnClick="" attribute rather than an OnClientClick="" attribute, as for asp:Button?
For example, this works:
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
and this doesn't (no error):
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
but this works:
<asp:Button runat="server" OnClientClick="alert('Hi');" />
and this doesn't (compile time error):
<asp:Button runat="server" OnClick="alert('hi');" />
(I know what Button.OnClick is for; I'm wondering why CheckBox doesn't work the same way...)
That is very weird. I checked the CheckBox documentation page which reads
<asp:CheckBox id="CheckBox1"
AutoPostBack="True|False"
Text="Label"
TextAlign="Right|Left"
Checked="True|False"
OnCheckedChanged="OnCheckedChangedMethod"
runat="server"/>
As you can see, there is no OnClick or OnClientClick attributes defined.
Keeping this in mind, I think this is what is happening.
When you do this,
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
ASP.NET doesn't modify the OnClick attribute and renders it as is on the browser. It would be rendered as:
<input type="checkbox" OnClick="alert(this.checked);" />
Obviously, a browser can understand 'OnClick' and puts an alert.
And in this scenario
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
Again, ASP.NET won't change the OnClientClick attribute and will render it as
<input type="checkbox" OnClientClick="alert(this.checked);" />
As browser won't understand OnClientClick nothing will happen. It also won't raise any error as it is just another attribute.
You can confirm above by looking at the rendered HTML.
And yes, this is not intuitive at all.
Because they are two different kinds of controls...
You see, your web browser doesn't know about server side programming. it only knows about it's own DOM and the event models that it uses... And for click events of objects rendered to it. You should examine the final markup that is actually sent to the browser from ASP.Net to see the differences your self.
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
renders to
<input type="check" OnClick="alert(this.checked);" />
and
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
renders to
<input type="check" OnClientClick="alert(this.checked);" />
Now, as near as i can recall, there are no browsers anywhere that support the "OnClientClick" event in their DOM...
When in doubt, always view the source of the output as it is sent to the browser... there's a whole world of debug information that you can see.
You are right this is inconsistent. What is happening is that CheckBox doesn't HAVE an server-side OnClick event, so your markup gets rendered to the browser. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox_events.aspx
Whereas Button does have a OnClick - so ASP.NET expects a reference to an event in your OnClick markup.
For those of you who got here looking for the server-side OnClick handler it is OnCheckedChanged
I was cleaning up warnings and messages and see that VS does warn about it:
Validation (ASP.Net): Attribute 'OnClick' is not a valid attribute of element 'CheckBox'. Use the html input control to specify a client side handler and then you won't get the extra span tag and the two elements.
Asp.net CheckBox is not support method OnClientClick.
If you want to add some javascript event to asp:CheckBox you have to add related attributes on "Pre_Render" or on "Page_Load" events in server code:
C#:
private void Page_Load(object sender, EventArgs e)
{
SomeCheckBoxId.Attributes["onclick"] = "MyJavaScriptMethod(this);";
}
Note: Ensure you don't set AutoEventWireup="false" in page header.
VB:
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
SomeCheckBoxId.Attributes("onclick") = "MyJavaScriptMethod(this);"
End Sub
You can do the tag like this:
<asp:CheckBox runat="server" ID="ckRouteNow" Text="Send Now" OnClick="checkchanged(this)" />
The .checked property in the called JavaScript will be correct...the current state of the checkbox:
function checkchanged(obj) {
alert(obj.checked)
}
You can assign function to all checkboxes then ask for confirmation inside of it. If they choose yes, checkbox is allowed to be changed if no it remains unchanged.
In my case I am also using ASP .Net checkbox inside a repeater (or grid) with Autopostback="True" attribute, so on server side I need to compare the value submitted vs what's currently in db in order to know what confirmation value they chose and update db only if it was "yes".
$(document).ready(function () {
$('input[type=checkbox]').click(function(){
var areYouSure = confirm('Are you sure you want make this change?');
if (areYouSure) {
$(this).prop('checked', this.checked);
} else {
$(this).prop('checked', !this.checked);
}
});
});
<asp:CheckBox ID="chk" AutoPostBack="true" onCheckedChanged="chk_SelectedIndexChanged" runat="server" Checked='<%#Eval("FinancialAid") %>' />
protected void chk_SelectedIndexChanged(Object sender, EventArgs e)
{
using (myDataContext db = new myDataDataContext())
{
CheckBox chk = (CheckBox)sender;
RepeaterItem row = (RepeaterItem) chk.NamingContainer;
var studentID = ((Label) row.FindControl("lblID")).Text;
var z = (from b in db.StudentApplicants
where b.StudentID == studentID
select b).FirstOrDefault();
if(chk != null && chk.Checked != z.FinancialAid){
z.FinancialAid = chk.Checked;
z.ModifiedDate = DateTime.Now;
db.SubmitChanges();
BindGrid();
}
gvData.DataBind();
}
}
One solution is with JQuery:
$(document).ready(
function () {
$('#mycheckboxId').click(function () {
// here the action or function to call
});
}
);

Resources