I am working on application where i want to pass data from one to another using Cache. On First page which is an .aspx page iI have a textbox control and one button Control. On button control click event i have written following code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(txtName.Text.Trim()))
{
Cache["Name"] = txtName.Text;
Response.Redirect("Test.html");
}
}
catch (Exception ex)
{
throw (ex);
}
}
Now on the Target page i.e Test.html i have written following code to get cache value
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
//var name = GetParameterValues('ID');
//var name = '<%= session.getAttribute("Name") %>';
var name = (string)["Name"];
alert(name);
});
but this code is not working. Please help me.
you should get cache value from server side not client (Javascript)
So it should be:
var name = '<%=Cache["Name"] %>';
btw. your test.html should be *.aspx site that way asp engine can parse it.
Or if it's completely different app to pass data you can not use cache !
One way to do this POST or GET methods.
Related
I have a page containing a jQuery ui tab control. That is working just fine.
The issue I have is saving the selected tab between PostBacks occuring from a DropDownList, without (offcourse) disabling those PostBacks.
I have following code on my aspx page and I receive no Javascript errors whatsoever:
<script>
var selected_tab = 1;
$(document).ready(function () {
var tabs = $("#rapportentabs").tabs({
activate: function (e, i) {
selected_tab = i.index;
}
});
selected_tab = $("[id$=selected_tab]").val() != "" ? parseInt($("[id$=selected_tab]").val()) : 0;
tabs.tabs("option", "active", selected_tab);
$("form").submit(function () {
$("[id$=selected_tab]").val(selected_tab);
});
});
</script>
<div id="rapportentabs">//containing the tabs itself</Div>
<asp:HiddenField ID="selected_tab" runat="server" />
I have following in my code behind:
protected void Page_Load(object sender, EventArgs e)
{
selected_tab.Value = Request.Form[selected_tab.UniqueID];
}
I've finally found a solution which seems to work perfectly
Just change the javascript part using direct reference to objects and use i.newTab.index() instead of i.index
The correct script should read as:
<script>
var selected_tab = 1;
$(document).ready(function () {
var tabs = $("#rapportentabs").tabs({
activate: function (e, i) {
selected_tab = i.newTab.index();
$("#selected_tab").val(selected_tab);
}
});
selected_tab = $("#selected_tab").val() != "" ? parseInt($("#selected_tab").val()) : 0;
tabs.tabs("option", "active", selected_tab);
$("form").submit(function () {
$("#selected_tab").val(selected_tab);
});
});
</script>
One option is to save the selected_tab in a localstorage and then restore it when the page loads - this will have a side affect of saving the selected tab not only when you post but also when you close the tab and reopen it.
Another option, much better IMHO, is to post the form with Ajax and this way you will not get a page refreshed at all - but this will mean you have to update whatever page changes, which may be lots of work if you have lots of server side rendering code.
I'm trying to determine the client window size on pageload, to use in creating a bitmap using c#. From reading on SO and elsewhere, I know that one method would be to:
Write a Javascript function to get the relevant values;
Store these in hidden fields;
Read the value using the code behind (c#) and then do stuff with it.
However, I'm getting tripped up by the execution sequence that runs code behind BEFORE any Javascript, even though I've set <body onload... to get and set the relevant values. (see below)
I know the rest of my code works, because, when I execute, the page shows the word "by" and the button. Then, after I have clicked the button and the page reloads, it can now suddenly read the two hidden values.
My question is, how can I get my c# Page_Load code to get those two hidden values from the client side, before it executes the rest of my code, and without the need for user action like clicking a button?
My page:
<body onload="getScreenSize()">
<form id="form1" runat="server">
<input type="hidden" name="hiddenW" ID="hiddenW" runat="server" />
<input type="hidden" name="hiddenH" ID="hiddenH" runat="server" />
<script>
function getScreenSize() {
var myW = document.getElementById("hiddenW");
myW.value = window.innerWidth;
var myH = document.getElementById("hiddenH");
myH.value = window.innerHeight;
}
</script>
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
</body>
Code behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(hiddenW.Value+" by " +hiddenH.Value);
}
}
On first run (when I need those values), it shows
and after I click the button, it proves the Javascript works:
The question then, is how do I get those values before the rest of my Page_Load code runs, so that I can go straight into generating and displaying my image?
You cannot get the client window size before the C# Page_Load() executes because the page is rendered to the client after the C# code execution is complete.
The window size may change during page load, hence you have to get the window size only after page load is complete.
Solution:
You can use ajax to send the values to the back-end, after the page has loaded completely.
OR
You can cause a post-back using java-script after you get the correct value, this way:
JQuery:
$(function() {
var width = window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
var height = window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
$('#hdn_width').val(width);
$('#hdn_height').val(height);
$('#your_form').submit();
});
C#:
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (IsPostBack)
{
// Use hdn_width and hdn_height here
}
}
catch (Exception ex)
{
}
}
Use the IsPostBack property
This would solve your problem
For Example
if(!Page.IsPostBack)
{
//Control Initialization
//Your code goes here
}
I used a timer to postback once and two none-displayed textboxes to store the window-values width and height. the textboxes are filled with a javascript:
document.getElementById('<%=TxWd.ClientID %>').value = window.innerWidth;
document.getElementById('<%=TxHt.ClientID %>').value = window.innerHeight;
In code behind (VB.NET):
Protected Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Session("seswidth") = Val(TxWd.Text)
Session("sesheigth") = Val(TxHt.Text)
Timer1.Enabled = False
End Sub
I had a form which is called contact.aspx and it has a dropdown which includes user list.
I add below line to add user.
New User
and the javascript of insertUser is below:
<script type="text/javascript">
function insertUser() {
var win = window.open('stackoverflow.aspx?t=1', 'User Insert', 'width=800,height=600');
}
</script>
And when I click "New User", stackoverflow.aspx is opened and I want to enter new user data and click save.
After clicking save buton, how can I close stackoverflow.aspx and only refresh dropdown at the contact.aspx?
You can use the following Javascript code to close child window and refresh parent(ref):
window.close();
if (window.opener && !window.opener.closed) {
window.opener.location.reload();
}
or you can do partial refresh. see here
you must stored variable in session , db or ...
and use this link.
http://forums.asp.net/t/1606853.aspx/1
Don't do this on different page, because you can't update your field from an other page. You can make ajax requests from the contact.aspx by intervals, and you can check the DB if there is a new user, and refresh it. But it's not a nice solution. So I suggest to make this registration (which is on stackoverflow.aspx) on contact.aspx, inside an iframe or just inside a div. You can hide each content in each action (when you are registering, hide the rest of content just display the registration fields, if you are done refresh the dropdownlist reset your registration fields and hide them, display the dropdownlist).With this approach you can refresh your dropdownlist, when you are done with registration.
To refresh dropdownlist make an ajax call, where you can get the new values from the db (there can be multiple new values submitted by different user at the same time) and then you cen refresh dropdown (wich is a select with options in HTML) But if you do this, you can get an eventvalidation error, which is a built in asp.Net feature (defends against xss attack). So the solution can be to make a full postback after registration, and refresh the values by server code, or don't use server control to dropdownlist, only html select, and fill it on document ready, and refresh it async by javascript or jQuery.
mmm, On the stackoverflow.aspx after user clicks save, it posts to the server, creates a new user and get a JSON representation of the object. then register a script to close the window and pass the json to the opener.
private btnSave_Click(object sender, EventArgs args)
{
//Save data
...
string objectJson = GetJSON(); // {"userId": 100, "name": "John Smith"}
ClientScriptManager cs = Page.ClientScript;
StringBuilder cstext1 = new StringBuilder();
cstext1.Append("<script type=text/javascript> window.opener.appendObject(" + objectJson + ") </");
cstext1.Append("script>");
cs.RegisterStartupScript(this.GetType(), "RefreshScript", cstext1.ToString());
}
On the contacts.aspx have the following script:
<script type="text/javascript">
function appendObject(json) {
var obj = JSON.parse(json); //convert json to object
//Add item to the drop down list.
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.text = obj.name;
try
{
// for IE earlier than version 8
x.add(option, x.options[null]);
}
catch (e)
{
x.add(option,null);
}
}
</script>
Didn't test it but I think it works.
How can i assign value to javasctipt variable from code-behind (C#)?
<script type="text/javascript">
String.prototype.trim = function () { return this.replace(/^\s+|\s+$/, ''); };
function ConstantByCode(_Obj, _Div) {
var pl = new SOAPClientParameters();
_Obj.value = _Obj.value.trim();
pl.add("Code", _Obj.value);
pl.add("Group", _Obj.Grp);
alert(_Obj.Grp);
var _Value = SOAPClient.invoke("ConstantWS.asmx", "GetConstantByCode", pl, false, CallBackEvent);
if (_Value == null || _Obj.value == "" || _Obj.value == null || IsNumeric(_Obj.value) == false) {
_Obj.value = "";
_Div.innerHTML = "";
}
else {
_Div.innerHTML = _Value;
}
}
function CallBackEvent(r) {
}
function IsNumeric(input) {
return (input - 0) == input && input.length > 0;
}
BehindCode
txtCode.Attributes.Add("Grp", Me.ConstValue)
txtCode.Attributes.Add("onchange", "ConstantByCode(this," & DivTitle.ClientID & ");")
txtCode.Attributes.Add("onkeyup", "ConstantByCode(this," & DivTitle.ClientID & ");")
_obj.Grp has now value.
alert said : undefined
I see that you want to retrieve value of Grp that is a custom attribute. You need to use getAttribute function - so instead of _Obj.Grp, you need to use _Obj.getAttribute("Grp").
Also, I see that you are not enclosing client id in quotes from ode-behind. So instead of
txtCode.Attributes.Add("onchange", "ConstantByCode(this," & DivTitle.ClientID & ");")
you need to say
txtCode.Attributes.Add("onchange", "ConstantByCode(this,'" & DivTitle.ClientID & "');")
Note the single quote(') around the client id.
Further, ConstantByCode js function appears to be taking div element. Hence, you need to add line to it for converting from client id to actual DOM. i.e.
function ConstantByCode(_Obj, _Div) {
_Div = document.getElementById(_Div);
.... // rest of the code
Firstly you will need to have access to the value on the client. We can do this by storing the value in a hiddenfield or by adding an attribute to the control. It seems you wish to do this by using an attribute so lets do this first.
add the following to your page_load method so we have access to the C# value on the client.
protected void Page_Load(object sender, EventArgs e)
{
string requiredJSValue = "put your value here";
txtCode.Attributes.Add("CSCodeAttribute", requiredJSValue);
}
We then need to access this value through Javascript. Firstly we will need to get the client ID of the control as C# will set this value. Note. I am using Jquery to retrieve the control ID. This is not required, however I prefer it. Jquery is a framework for javascript and can be downloaded from www.jquery.com
function GetCSAttributeValue()
{
var csControlID = $('#<%= txtUOMCost.ClientID %>'); //Gets the control name.
var requiredJSValue = csControlID .attr("CSCodeAttribute"); //Value stored in variable.
}
I'm not 100% sure but I think you'll need a workaround to get this working. Because logically at the backend the javascript variable doesn't even exist. You can probably create a hidden field and make it a bridge between the javascript variable and code behind. Check this: http://forums.devx.com/showthread.php?t=164356
Try this:
1. Add a hidden field in you .aspx page:
<asp:HiddenField ID="hidden" runat="server" />
2. Change the value of this field in your code-behind:
protected void Page_Load(object sender, EventArgs e)
{
hidden.Value = "hello";
}
3. Write the following script to access the value and put it in any variable:
<script type="text/javascript">
if (document.getElementById("MainContent_hidden") != undefined) {
var hiddenVal = document.getElementById("MainContent_hidden").value;
}
else {
var hiddenVal = null;
}
</script>
WARNING: The third part is tricky. We are not using the same ID that we provided in the 1st step when we are calling the getElementById function. This is because asp.net changes this and the temporary workaround is to run the page once and view its source. Check the id of the hidden field and put it in step 3 inside the getElementById function. You can look for better alternatives but for now use this if you want. If you're struck at step 3, let me know.
I don'see how your question is related to the code...
But to set a value of a javascript value from serverside... well you can't, because server side code runs precisely in the server and way before the HTML goes to the client and javascript gets executed.
But what you can do is make your server side code generate a piece of javascript that holds your value.
<script type="text/javascript">
var x = <%= ServerSideMethod() %>;
</script>
So I now have the following jquery to hide or show a textbox based on specific values selected in a DropDownList. This works except that I need the first display of the popup to always be hidden. Since no index change was made in the drop down list, the following does not work for that. If I code it as visible="false", then it always stays hidden. How can I resolve this?
<script language="javascript" type="text/javascript">
var _CASE_RESERVE_ACTION = "317";
var _LEGAL_RESERVE_ACTION = "318";
function pageLoad() {
$(".statusActionDDLCssClass").change(function() {
var value = $(this).val();
if (value == _CASE_RESERVE_ACTION || value == _LEGAL_RESERVE_ACTION) {
$(".statusActionAmountCssClass").attr("disabled", false);
$(".statusActionAmountCssClass").show();
}
else {
$(".statusActionAmountCssClass").attr("disabled", true);
$(".statusActionAmountCssClass").hide();
}
});
}
</script>
Thank you,
Jim in Suwanee, GA
If you set
visible=false
.Net will not render it. You can do
style="display:none;"
and .Net will render the tag properly but CSS will hide it from the user.
Add the following to pageLoad function
function pageLoad(sender, args) {
$("input.statusActionAmountCssClass").hide();
.... rest of code .....
}
By the way, I would recommend using the selector $("input.statusActionAmountCssClass") to get a jQuery object containing a reference to your input, otherwise jQuery will search all elements to match the CSS class .statusActionAmountCssClass
EDIT:
Another change that could also be made is to use jQuery's data() to store the two global variables
$.data(window, "_CASE_RESERVE_ACTION","317");
$.data(window, "_LEGAL_RESERVE_ACTION","318");
then when you need them simply cache the value in a local variable inside the function
function someFunctionThatNeedsGlobalVariableValues() {
var caseReserveAction = $.data(window, "_CASE_RESERVE_ACTION");
var legalReserveAction = $.data(window, "_LEGAL_RESERVE_ACTION");
}
this way, the global namespace is not polluted. See this answer for more on data() command