I have created a drop down list in my user control, see source code below,
<asp:DropDownList ID="ddlInd" runat="server" DataSourceID="indXmlDS" DataTextField="text" DataValueField="text"></asp:DropDownList>
In Page_load I have done this:
protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(this.GetType(), "myScript", "<script language='javascript' src='../Scripts/myJS.js'></script>");
ddlInd.Attributes["onchange"] = "showTextbox()";
}
So what code should I be using, if I would like to refer to this control in my external javascript file, myJS.js?
I have tried to use document.getElementById("<%=ddlInd.ClientID %>") but it would return NULL.
Can anyone help? Thanks
EDIT:
Not sure if attaching that myJS.js file would be helpful here
function showTextbox() {
var sid = <%=ddlInd.ClientID %>;
//alert(sid);
var s = document.getElementById('<%=ddlInd.ClientID %>'); // <-- problem here
alert(s);
if (s.options[s.selectedIndex].value == "Other") {
myDiv.style.display = "inline";
alert("display");
}
else {
myDiv.style.display = "none";
alert("none");
}
}
EDIT2:
I kinda found the workaround which is to embed scripts in the user control page instead of using external script file. Thanks for the suggestions everyone. They were all very helpful.
Also the modified js script is as follows, and it works:
function showTextbox(objID) {
var s = document.getElementById(objID);
var div = document.getElementById("myDiv");
if (s.options[s.selectedIndex].value == "Other") {
div.style.display = "inline";
}
else {
div.style.display = "none";
}
}
Try using ClientScriptManager.RegisterClientScriptInclude instead of RegisterStartupScript.
It seems in your case you're including an external javascript file, rather than javascript code that should directly appear in the page.
Also try changing the double quotes " to single quotes ' in document.getElementById('<%=ddlInd.ClientID %>')
EDIT oh, I see that you're trying to do <%=ddlIndustry.ClientID %> inside your javascript file. That is not going to be interpreted in an external js file! You should either include your function directly in teh page (not as an external file) or try to pass the ColntrolId as an argument to the js function
Try to set the ClientIdMode of the control to Predictable:
<asp:DropDownList ID="ddlInd" ClientIDMode="Predictable" runat="server" DataSourceID="indXmlDS" DataTextField="text" DataValueField="text"></asp:DropDownList>
You can also use a static ClientId by using ClientIDMode="Static" in which case the ClientId will be equal to the id of the control, so you can say:
document.getElementById("ddlInd");
you could use this to reference your control to .js file
$('select#ddlInd').val(....)
if the dropdownlist is inside a "ContentPlaceholder", you could do this
$('select#ContentPlaceholderID_ddlInd').val(...)
place it in your .js file
Note : include of course your .js file
If you can't use .NET 4.0 and are stuck on 3.5/2.0, I wrote a small library called Awesome.ClientID to solve this problem.
I've posted it before in this answer: How do I make this getElementsbyName work for IE (and FF)?
Basically it will allow you to serialize all your controls to a JSON array, and you can change your JavaScript to:
document.getElementById(controls.ddlInd);
The library can be found here: http://awesomeclientid.codeplex.com/
Blog post about it: http://www.philliphaydon.com/2010/12/i-love-clean-client-ids-especially-with-net-2-0/
You can use <%=Control.ClientID %> When you have script on the .aspx page if your using an External file then u have to use the control id <%=ddlInd.ClientID %> will not work.
Related
How to you code an <a href="... tag in ASPX to call a simple code behind function?
I have inherited a bit of code. I did not write this originally but I am trying to modify it.
In the steppayment.aspx file there are lots of "<a href..." tags that target either a whole URL or another aspx file.
But what if I only want to call a function in the code-behind, steppayment.aspx.cs?
In the aspx file, steppayment.aspx, I have this line of code:
<u><b><a href="fsModifyVisualContentonPaypal();" >Click here</a></b></u> now to open the PayPal payment window.
In the code behind, steppayment.aspx.cs, I have this line of code:
protected void fsModifyVisualContentonPaypal()
{
fsCreditCard.Visible = false;
fsAfterCreditCard.Visible = true;
}
I have break points in this function. It never gets here. When the user clicks on the "click here" it throws an error.
Use a LinkButton control instead of a basic HTML anchor tag
<asp:LinkButton OnClick="fsModifyVisualContentonPaypal" runat="server" Text="Click here" />
To call client side methods like javascript you would use OnClientClick. You'll want to check out the documentation for LinkButton on MSDN
If it you want it to work on postback, try an ASP.NET LinkButton control.
This is from memory, but it would be something like this:
<u><b><asp:LinkButton OnClick="fsModifyVisualContentonPaypal" runat="server">Click here</asp:LinkButton></b></u>
If you want it to work without a postback, that gets you into either Ajax territory or plain JavaScript. (Or, you might look up the ASP.NET UpdatePanel.)
All of this is assuming that you're using ASP.NET WebForms. If you're using MVC, that's another topic.
Both answers would work. You need to change the event method signature as well like this:
protected void fsModifyVisualContentonPaypal(object sender, EventArgs e)
{
fsCreditCard.Visible = false;
fsAfterCreditCard.Visible = true;
}
And your link button should look like this ( as suggesested by both answers):
<u><b><asp:LinkButton OnClick="fsModifyVisualContentonPaypal" runat="server">Click here</asp:LinkButton></b></u>
I'm working on an ASP.Net project, with C#.
Usually, when I need to put Buttons that will execute some methods, I will use the ASP Controller (Button) inside a runat="server" form.
But I feel that this really limits the capabilities of my website, because when I used to work with JSP, I used jquery to reach a servlet to execute some codes and return a responseText.
I did not check yet how this is done in ASP.Net, but my question concerns controllers and the famous runat="server".
When I add a runat="server" to any HTML Element, I'm supposed to be able to manipulate this HTML element in C# (Server-Side), and this actually works, I can change the ID, set the InnerText or InnerHtml, but the thing that I can't get, is why can't I execute a method by clicking on this element?
The "onclick" attribute is for JavaScript I think, and OnServerClick doesn't seem to work as well. Is it something wrong with my codes? or this doesn't work at all?
You will have to handle the click in the div using the Jquery and call
server-side methods through JQuery
There are several way to execute server side methods by clicking on a div or anything on your page. The first is mentioned __dopostback, second is handling the click in javascript or with jQuery and calling a function in a handler or a page method in a webservice or a page method in your page behind code.
Here is the handler version:
$("#btn1").click(function() {
$.ajax({
url: '/Handler1.ashx?param1=someparam',
success: function(msg, status, xhr) {
//doSomething, manipulate your html
},
error: function() {
//doSomething
}
});
});
I think the second version is better, because you can make a partial postback without any updatepanel, asyncronously. The drawback is, the server side code is separated from your page behind code.
Handler:
public class Handler1: IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
var param1= context.Request.QueryString["param1"];
//param1 value will be "someparam"
// do something cool like filling a datatable serialize it with newtonsoft jsonconvert
var dt= new DataTable();
// fill it
context.Response.Write(JsonConvert.SerializeObject(dt));
}
}
If everything is cool, you get the response in the ajax call in the success section, and the parameter called "msg" will be your serialized JSON datatable.
You can execute a method from jquery click in server, using __doPostBack javascript function, see this threat for more details How to use __doPostBack()
Add this code in your jquery on div onclick and pass DIv id whcih call click
__doPostBack('__Page', DivID);
On page load add this code
if (IsPostBack)
{
//you will get id of div which called function
string eventargs = Request["__EVENTARGUMENT"];
if (!string.IsNullOrEmpty(eventargs))
{
//call your function
}
}
Make the div runat="server" and id="divName"
in page_Load event in cs:
if (IsPostBack)
{
if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"] == "divClick")
{
//code to run in click event of divName
}
}
divName.Attributes.Add("ondivClick", ClientScript.GetPostBackEventReference(divName, "divClick"));
Hope it helps :)
if you are referring to divs with runat="server" attributes, they don't have onserverclick events, that's why it doesn't work
I'm using ajaxFileUpload as described here: http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/AjaxFileUpload/AjaxFileUpload.aspx
It is working fine except when I have multiple file upload controls on the same page. Specifically, I am trying to upload different files for different questions. When I upload the first on the page, it works fine, but the one lower down on the page will only upload it's file into the answer for the first question.
I'm not sure that makes sense... so it may help you to know that my page is populated with questions dynamically using ascx files. The document ascx file looks like this:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Document.ascx.cs" Inherits="ScholarshipApplication.controls.questions.Document" %>
<ajaxToolkit:AjaxFileUpload OnUploadComplete="UploadComplete" ID="FileUploadControl" MaximumNumberOfFiles="1" runat="server" AllowedFileTypes="png,jpg,jpeg,pdf,tiff,tif,gif" />
<asp:LinkButton ID="downloadButton" runat="server" CausesValidation="false" OnClick="downloadButton_Click" />
And the code behind:
public void UploadComplete(object sender, AjaxFileUploadEventArgs e)
{
entry.data = e.FileName;
entry.setDocumentData(e.GetContents());
this.downloadButton.Text = e.FileName;
}
My initial thoughts are that somehow I need to help the control's generated javascript to know which question it should be triggering when.
I believe this is a bug in control or this was implemented by some non-obvious reason. Actually, this control doesn't support multiple instances on a page. Consider to use AsyncFileUpload control instead or customize a bit sources of the AjaxFileUpload control. If you prefer second option then you need to download sources from here: http://ajaxcontroltoolkit.codeplex.com/SourceControl/BrowseLatest and change AjaxFileUpload.cs file (here is a path: /Server/AjaxControlToolkit/AjaxFileUpload/AjaxFileUpload.cs). What you need to do is to change ContextKey constant to property for combining context key guid with unique id of control:
public class AjaxFileUpload : ScriptControlBase
{
private const string ContextKeySuffix = "{DA8BEDC8-B952-4d5d-8CC2-59FE922E2923}";
private string ContextKey
{
get { return this.UniqueID + "_" + ContextKeySuffix; }
}
Actually, if you'll look on PreRender method of AjaxFileUpload class you'll easy realize reson for such behavior of this control (the first control handle uploads from all sibling controls on a page).
as per my understanding You need a hidden field variable to identify your question id IN UserControl:
<input type="hidden" id="hdnQuestionId" runat="server"/>
while populating/generating question you need to set this variable , and when you upload the doc , fetch this hidden value and use it.
I created a data attribute named "data-upload-type" on ALL AjaxFileUpload controls and set it to the name of the type. Then I set up the client call to grab that value and set a cookie with the same value. The cookie IS received on the server side functions and I branch based on the value I receive.
Here is an example:
function StartUpload(sender, args) {
var t = $(sender._element).attr('data-upload-type');
document.cookie = 'upload-type=' + $(sender._element).attr('data-upload-type') + ';';
}
<asp:AjaxFileUpload ID="afuUploader1" runat="server" OnClientUploadStart="StartUpload" OnUploadComplete="UploadComplete" OnClientUploadComplete="UploadComplete" data-upload-type="UploadType2"></asp:AjaxFileUpload>
Then in your server side upload call simply check Response.Cookies("upload-type").
Works like a charm!
I don't know how to set the value of a hiddenField in Javascript. Can somebody show me how to do this?
Javascript:
document.getElementById('hdntxtbxTaksit').value = "";
HTML:
<asp:HiddenField ID="hdntxtbxTaksit" runat="server" Value="" Visible="false"> </asp:HiddenField>
error : "Unable to get value of the property \'value\': object is null or undefined"
Prior to ASP.Net 4.0
ClientID
Get the client id generated in the page that uses Master page. As Master page is UserControl type, It will have its own Id and it treats the page as Child control and generates a different id with prefix like ctrl_.
This can be resolved by using <%= ControlName.ClientID %> in a page and can be assigned to any string or a javascript variables that can be referred later.
var myHidden=document.getElementById('<%= hdntxtbxTaksit.ClientID %>');
Asp.net server control id will be vary if you use Master page.
ASP.Net 4.0 +
ClientIDMode Property
Use this property to control how you want to generate the ID for you. For your case setting ClientIDMode="static" in page level will resolve the problem. The same thing can be applied at control level as well.
asp:HiddenField as:
<asp:HiddenField runat="server" ID="hfProduct" ClientIDMode="Static" />
js code:
$("#hfProduct").val("test")
and the code behind:
hfProduct.Value.ToString();
First you need to create the Hidden Field properly
<asp:HiddenField ID="hdntxtbxTaksit" runat="server"></asp:HiddenField>
Then you need to set value to the hidden field
If you aren't using Jquery you should use it:
document.getElementById("<%= hdntxtbxTaksit.ClientID %>").value = "test";
If you are using Jquery, this is how it should be:
$("#<%= hdntxtbxTaksit.ClientID %>").val("test");
document.getElementById('<%=hdntxtbxTaksit.ClientID%>').value
The id you set in server is the server id which is different from client id.
try this code:
$('hdntxtbxTaksit').val('test');
I suspect you need to use ClientID rather than the literal ID string in your JavaScript code, since you've marked the field as runat="server".
E.g., if your JavaScript code is in an aspx file (not a separate JavaScript file):
var val = document.getElementById('<%=hdntxtbxTaksit.ClientID%>').value;
If it's in a separate JavaScript file that isn't rendered by the ASP.Net stuff, you'll have to find it another way, such as by class.
My understanding is if you set controls.Visible = false during initial page load, it doesn't get rendered in the client response. My suggestion to solve your problem is
Don't use placeholder, judging from the scenario, you don't really need a placeholder, unless you need to dynamically add controls on the server side. Use div, without runat=server. You can always controls the visiblity of that div using css.
If you need to add controls dynamically later, use placeholder, but don't set visible = false. Placeholder won't have any display anyway, Set the visibility of that placeholder using css. Here's how to do it programmactically :
placeholderId.Attributes["style"] = "display:none";
Anyway, as other have stated, your problems occurs because once you set control.visible = false, it doesn't get rendered in the client response.
I will suggest you to use ClientID of HiddenField. first Register its client Id in any Javascript Variable from codebehind, then use it in clientside script. as:
.cs file code:
ClientScript.RegisterStartupScript(this.GetType(), "clientids", "var hdntxtbxTaksit=" + hdntxtbxTaksit.ClientID, true);
and then use following code in JS:
document.getElementById(hdntxtbxTaksit).value= "";
Try setting Javascript value as in document.getElementByName('hdntxtbxTaksit').value = '0';
I'm trying to read the value of a C# property from my code behind file into some JQuery script (see below). The JQuery selector I've written accesses an ASP.Net GridView and then a CheckBox field within the gridview. Whenever a checkbox is checked or un-checked the code is hit, but I need to access the C# property from the code behind to take the appropriate action based on the value of the property.
$(".AspNet-GridView-Normal > td > input").click(function() {
//Need to access the C# property here
//Take action here based on the value of the C# property
});
This may be stating the obvious, but the code behind doesn't exist on the client side where your jQuery code is executing. What you could do is assign the value of the property to a hidden field on the server side so that when you need to check it with jQuery on the client side it will be available. So you might do the following on the client side.
Markup:
<asp:HiddenField ID="hfValueINeedToKnow" runat="server"/>
Code Behind:
hfValueINeedToKnow.Value = <some value>;
jQuery:
$("#<%= hfValueINeedToKnow.ClientID %>").val();
You might need to make some minor changes to support a value for each row of the grid, but hopefully this explains the general idea.
You mentioned in a comment that the value is an int. And I see it's also a public property in your codebehind. This is trivial now - you don't need to escape the value, nor access it in some round-about way, and you get type safety for free:
<script>
$(".AspNet-GridView-Normal > td > input").click(function() {
var AvailableInstalls = <%= AvailableInstalls %>;
});
</script>
Well you can't.
You need to render the C# property in some element (perhaps a hidden field) and then look at it that way.
But explain further: What property are you trying to check?
What I've done for this scenario in the past is to print out my code value into the markup and store whatever it is in a javascript variable, thus making a copy of it available to client-side code. This is a silly example, but hopefully it makes sense:
<%
var messsge = "Hello World!"
%>
<html>
<head>
<script type="text/javascript">
function ShowMessage()
{
var msg = '<%= message %>';
if(msg)
alert(msg);
}
</script>
</head>
</html>
There isn't a really clean way to do this. Your best bet would probably be to use the ClientScript.RegisterClientScriptBlock functionality built into ASP.NET. Here's a good primer.
private int myValue;
protected void Page_Load(object sender, EventArgs e) {
ClientScript.RegisterClientScriptBlock(typeof(Page),
"vars", "<script>var myParams = { p1: " + myValue + ", p2: 'My Name' };</script>");
}
This will put the supplied script on your page towards the top of the form. You can change that too. Obviously, it isn't the prettiest; you are essentially string concatenating a different language, but it will work, and for simple variable declaration isn't too rough on the eyes.
ASP Embedded in JavaScript always makes me nervous from the perspective of script injection attacks and the inability to unit-test your JavaScript.
This build upon an ealier answer:
<script type="text/javascript">
$(".AspNet-GridView-Normal > td > input").click(function() {
var AvailableInstalls = $("#MyHidden").val();
});
</script>
You could move it to a hidden variable:
<input type="hidden" id="#MyHidden" value="<%= AvailableInstalls %>" />
However this doesn't get around the problem of injection. So you could you could add a server-side hidden variable and set it from the Page_Load event function in ASP.NET.
(P.s. you also need the attribute type="text/javascript" in your script tag to make it valid HTML).
If you will put your value into an asp:HiddenField with id hfValueINeedToKnow, the simplest way to retrieve this value client side is
var jsvar = $("[id$=hfValueINeedToKnow]").val();
So you can also place this code in a separate .js file.