Access variablea of javascript in .aspx.vb file - asp.net

I want to access variables defined in Javascript in.aspx file to .aspx.vb file
How can i access variables in .aspx.vb file?
<script type="text/javascript" language="javascript">
var c=0;
var m=0;
var h=0;
var t;
var timer_is_on=0;
function startTMR()
{
document.getElementById('TimeLable').value=h+":"+m+":"+c;
c=c+1;
if(c==60)
{
c=0;
m=m+1;
if(m==60)
{
m=0;
h=h+1;
}
}
t=setTimeout("startTMR()",1000);
}
function doTimer()
{
if (!timer_is_on)
{
timer_is_on=1;
startTMR();
}
}
This is simple javascript I'm using in my .aspx page
now i want to access the variable h m and c in .aspx.vb page how to do that?

You'll need to save that javascript variable into a hidden input, which will post with your form when you do a postback. You'll be able to access the value via:
string value = Request.Form["hiddenName"];
Assuming you declare your hidden input like this:
<input type="hidden" id="hiddenValue" name="hiddenName" />
You can set this value like this with native JavaScript:
document.getElementById("hiddenValue").value = "12";
or with jQuery like this:
$("#hiddenValue").val("12");
If you'd like to make sure this hidden input is automatically saved to the JavaScript variable x before you post back, you could do the following with jQuery
$("#form1").submit(function () {
$("#hiddenValue").val(x);
});
Or this with native JavaScript:
document.getElementById("form1").addEventListener("submit", function () {
document.getElementById("hiddenValue").value = x;
});
If you're not using jQuery, and you opt for this native option, just make sure you put the script at the bottom of the body section; do not put this script in the head, since the dom is not formed yet, and you will get a null error.
And obviously this all assumes your form element looks like this:
<form id="form1" runat="server">
if yours has a different id, then adjust accordingly.

Related

Jquery chosen multiple select, How to get selected values server side in asp.net?

I am revitalizing a very old application and trying not to introduce Devexpress or Telerik into this application.
I have a need for some dropdownlists with multiple selection availability. I have poked around on the web and the chosen jquery plugin looks to be the route to go.
I have it implemented in one of my test pages, but I am trying to get this implemented rather quickly without much tooling around with it. I am having some difficulties grabbing the multiple selected values on the server side in my code behind. I don't really want to have a bunch of client side functionality holding and maintaining data on change etc.
Any one ever attempt to get at this data server side versus client side and have luck?
Code example. :
<select id="slcExample" multiple class="chosen-select" style="width:350px;" runat="server"></select>
<script type="text/javascript">
$(document).ready(function () {
var config = {
'.chosen-select': {},
'.chosen-select-deselect': { allow_single_deselect: true },
'.chosen-select-no-single': { disable_search_threshold: 10 },
'.chosen-select-no-results': { no_results_text: 'Oops, nothing found!' },
'.chosen-select-width': { width: "95%" }
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
});
</script>
I have found that if I could get at this property .SelectedIndices that I would have access to the selected values but it will not let me use this on the server side as it is a protected property of the select in asp.net.
Here is what I ended up doing. :
Dim index As Integer
Dim valuesChosen As String = ""
For index = 0 To (slcExample.Items.Count - 1)
If (slcExample.Items(index).Selected) Then
valuesChosen += slcExample.Items(index).Value.Trim + ";"
End If
Next
I needed something on the server side. Hopefully this helps someone else. If you have a better option I am open to seeing it and will mark as answer if better.
You can create a hidden field with asp:net class. with a javascript method, add all value in a comma separated list.
You can have the list on the server side after submiting your form.
try putting clientIDMode="Static"
<asp:HiddenField runat="server" ID="hidTest" ClientIDMode="Static" />
but if you can't, you will have to see the generated name from asp to update it in your javascript method
<script type="text/javascript">
$(document).ready(function () {
var config = {
'.chosen-select': {},
'.chosen-select-deselect': { allow_single_deselect: true },
'.chosen-select-no-single': { disable_search_threshold: 10 },
'.chosen-select-no-results': { no_results_text: 'Oops, nothing found!' },
'.chosen-select-width': { width: "95%" }
}
var hiddenSeparatedList = "";
for (var selector in config) {
hiddenSeparatedList += $(selector).chosen(config[selector]) + ','
$('#hidTest').val(hiddenSeparatedList);
}
});
</script>
I had the same problem and switched to this JQuery plugin instead: http://www.erichynds.com/blog/jquery-ui-multiselect-widget
Since the asp.net dropdown control does not allow multiple items, I used a regular tag with runat server and an ID. The plugin actually selects the items and then you can read them from code behind.
The plugin will works client-side on the asp.net dropdown, but you can't get the selected items in the code behind. So depending on your needs .. .
Hope this helps!
Bonnie
I used a List instead:
int i;
IList<string> chosenItems = new List<string>();
for (i = 0; i <= selectExample.Items.Count - 1; i++)
{
if (selectExample.Items[index].Selected)
{
chosenItems.Add(selectExample.Items[index].Value.Trim());
}
}

Using conditional compile constants to control JavaScript emitted by an MVC3 view

I have gleaned that it is possible to use conditional compiler directives and constants in Razor markup. I would like to know if there is a way to conditionally emit JavaScript text using these directives, as I seek to to below:
#section BodyPanelScript
{
<script type="text/javascript">
$(function () {
$(":password").val(null);
// Back up current names of package radio buttons, then make all their names the same for grouping.
$("#package-selector :radio[name$='.IsSelected']").each(function () {
$(this).attr("oldname", $(this).attr("name"));
});
$("#package-selector :radio[name$='.IsSelected']").attr("name", "Package.IsSelected");
// Hook the 'submit' click to restore original radio button names.
$("form#register :submit").click(function () {
$(":radio[name='Package.IsSelected']").each(function () {
$(this).attr("name", $(this).attr("oldname"));
});
});
});
</script>
#{
#if AUTO_FILL_REG
<text>
<script type="text/javascript">
$(function () {
$(":password").val("123456");
});
</script>
</text>
#endif
}
}
The constant AUTO_FILL_REG is defined in my Debug configuration, and tells the controller to populate the registration model with default values, so I don't have to always complete the form to test the process. Existing values in the model are ignored on the password field, so I resort to some JavaScript to populate this field. I would like to have this JavaScript conditionally emitted, but several attempts like the code above either result in the #if...#endif text being literally rendered, and the password populated, or nothing being rendered, regardless of build configuration.
This is not a particularly elegant solution, but it is simple. You can make a simple class like this
public static ConditionalValue {
public static bool AUTO_FILL_REG {
get {
#if DEBUG
return true;
#else
return false;
#endif
}
}
}
and then just reference this in your aspx. This is just one example of where you could place this property. You could do it as constants as well, but you get the idea.

asp.net external JavaScript file doesn't find Control.ClientID

On load I'm both calling a JavaScript setTimeout() function that will hide a .NET Panel control, and hiding it in the code behind on first load. Clicking the save button will set the Panel to visible then reload the page at which point a setTimeout() function is called... so basically you click save, and see a panel with "Details Saved" for three seconds, at which point it disappears.
The problem is the external JavaScript file can't find _pDivAlert.ClientID (I've debugged and it returns null). It only works when the code is in a tag in the .aspx page. Any suggestions as to how I can either pass the client ID to the HideControl() function or find the ClientID from the external JS file?
Here's my code, any suggestions?
<script language="javascript" src="Forms.js" type="text/javascript"></script>
<body onload="ToggleAlert()">
<form id="form1" runat="server">
<script type="text/javascript">
//alert the user that the details were saved
function HideControl() {
var control = document.getElementById('<%=_pDivAlert.ClientID %>');
if(control != null)
control.style.display = 'none';
}
function ToggleAlert() {
setTimeout("HideControl()", 3000);
}
</script>
I've also tried sending the ClientID within the ToggleAlert() call, but that didn't work:
<body onload="ToggleAlert('<%=_pDivAlert.ClientID %>')">
External JS:
function HideControl(_c) {
var control = _c;
if (control != null)
control.style.display = 'none';
}
function ToggleAlert(_c) {
setTimeout("HideControl(_c)", 3000);
}
can you show your markup with the panel and the codebehind where you hide it?
there's a difference between setting the Visible property to false and setting the style display attribute to none- the first will not render the element at all, meaning there isn't anything rendered with the id you're looking for.
edit: it's probably because of the way you're calling HideControl in the timeout- this should be a function instead of a string.
try doing
function ToggleAlert(_c) {
setTimeout(
function () {
HideControl(_c);
}, 3000);
}
just for clarity, when you pass a string to setTimeout, it's evaluated and then run. the code chunk that eval produces will run in a different scope than your ToggleAlert method, and so _c won't be available at that time.
edit: you also need to actually get a reference to the control. you're passing the id string to ToggleAlert, which relays it to HideControl, which is expecting an object not a string.
function HideControl(_c) { // _c is the id of the element
var control = document.getElementById(_c);
if (control != null)
control.style.display = 'none';
}

attaching jquery function to a span from asp.net code

I am trying to add some jquery to span with a class added to it.
I am using asp.net and trying to use RegisterClientScriptBlock to attach the below code to my element. "cphMain_ed1" is hardcoded in this example however I would normally been passing a parameter here just for the ease of this.
<script language="javascript" type="text/javascript">
$(function () {
$('.closeButton').click(function () {
alert('called ok');
$("cphMain_ed1").slideUp();
});
});
</script>
My c# code looks like this
String csName = string.Format("ButtonClickScript_{0}", this.ID);
Type csType = this.GetType();
////// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
StringBuilder csText = new StringBuilder();
// csText.Append("<script type=\"text/javascript\"> HidePanel('" + this.ID + "')");
csText.Append("<script type=\"text/javascript\">DoIt()");
csText.Append("</script>");
cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
What am I doing wrong as the function is not been attached to the span with the class "closeButton"
ANy help would be great!!
If you add a class to that user control container you want to hide, so your result is something like this:
<div class="container">
<span class="closeButton">Close</span>
Other content here
</div>
Then you can do away with IDs and code-behind code altogether, and reduce your jQuery down to this:
$(function() {
$('.closeButton').click(function () {
$(this).closest('.container').slideUp();
});
});
Instead of relying on an ID, it just finds the thing you want to hide in relation to the .closebutton. In this case we're using .closest() to get the nearest element up the tree matching the selector...the class that was added to the container you want to close. There are other functions to find things relatively as well, the tree traversal functions, in case you have other situations where this can save you some code.

Will this jscript run inside a .ASCX page?

Will this run inside an ASCX file in my ASP.Net project?
I can't seem to get it to work, just wondered if there was some particular thing missing? Do i need to include "runat="server""?
<!--[if lte IE 6]>
<script type="text/javascript">
window.onload = function() {
var images = document.getElementById("GetQuote").getAttribute("ImageUrl");
for (var i = 0; i < images.length; i++) {
var image_png_src = images[i].src;
var image_gif_src = image_png_src.replace(".png", ".gif");
images[i].src = image_gif_src;
}
};
</script>
<![endif]-->
It appears that this JavaScript function is attempting to reference ASP.NET web control properties, which are not accessible from the client side. You can, however, reference the HTML entities that are output to the page by ASP.NET, along with their attributes.
Assuming your JavaScript code is code within the .ascx code, change this line:
var images = document.getElementById("GetQuote").getAttribute("ImageUrl");
To this:
var images = document.getElementById('<%=GetQuote.ClientID%>').getAttribute("src");
What this does is insert the client ID that ASP.NET creates for the GetQuote Image control so that it can be referenced from the client side. It also references the proper attribute of the HTML img element (src) that corresponds to the ImageUrl property of the server side Image control.
EDIT:
I noticed after seeing TheVillageIdiot's response (and reading your code a bit more closely, which I should have done initially) that you are trying to use the images variable as an array. It appears that you may be trying to match several image elements that contain the text "GetQuote" in their IDs (like GetQuote1, GetQuote2, etc.).
Assuming that you need to do this on the client side, and that you are not using a framework like jQuery, try this:
window.onload = function()
{
// get all img elements on the page and load them into an array
var images = document.getElementsByTagName("img");
// iterate through the image array
for (var i = 0; i < images.length; i++)
{
// check that the current image's id contains "GetQuote" (case sensitive)
if (images[i].id.indexOf("GetQuote") >= 0)
{
var image_png_src = images[i].src;
var image_gif_src = image_png_src.replace(".png", ".gif");
images[i].src = image_gif_src;
}
}
};
You don't need a runat="server" because this is code that will run on the client. It should work, but maybe you are having problems because you are referencing IDs on items that are asp.net controls? This would mean that your ID values would not match. If so you could solve this by using control.ClientID redndered into the JavaScript server-side to make them match.
If GetQuote is an aspx element then you need to replace it with <%= GetQuote.ClientID %> and ImageUrl with src like
var images = document.getElementById('<%=GetQuote.ClientID%>')
.getAttribute("src");
Also images should be one string not an array of strings so your loop is also at fault. Try this one instead:
var image = document.getElementById('<%=GetQuote.ClientID%>').
if(images){
var src = image.GetAttribute("src");
image.SetAttribute("src",src.replace(".png", ".gif");
}

Resources