javascript textbox_changed value - c#

here is my ASPX code
<%# Page Title="About Us" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="About.aspx.cs" Inherits="About" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script language="javascript" type="text/javascript">
function sum(t1)
{
var txt1 = document.getElementById('MainContent_TextBox2').value;
var result = parseInt(txt1) / 2;
var result1 = parseInt(result);
if (!isNaN(result))
{
document.getElementById(t1).value = result1;
}
}
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:TextBox ID="TextBox2" runat="server" onkeyup="sum('MainContent_TextBox3')"</asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server" ReadOnly="True"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"/>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
and my c# code is that
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class About : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox4.Text = TextBox3.Text;
}
}
the problem is that when i click on Button1 no error and TextBox4 is empty and i want that when i click on Button1 textbox3 value is transfered in textbox4.

It's because of the ReadOnly="True" that you have set on TextBox3.
When a control is set to ReadOnly in ASP.NET, the value that was placed into the control when the page was original rendered will not be updated.
Even if you change the value in the control on the browser (as you are doing), the value that is sent back to the server will not effect the value in the TextBox control - it will keep it's old value thanks to the ViewState.
The answer is to store the new value in a <asp:HiddenField>, which you should update at the same time as TextBox3.
Then on the server use the value in the hidden field, as that will contain the value you want. (Also, remember that you will need to update the value in the textbox from the hidden control as part of the postback).

Related

ASP.NET update labels separately and asynchronously

Ok so I can successfully update my page labels asynchronously using a timer. The problem is that the labels always update simultaneously while I want each one to update in sequence.
Here is my aspx:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:UpdatePanel runat="server" id="UpdatePanel1"
UpdateMode="Conditional">
<contenttemplate>
<asp:Timer id="Timer1" runat="server"
Interval="5000"
OnTick="Timer1_Tick">
</asp:Timer>
<asp:Label ID="Label1" runat="server" >Label1</asp:Label>
<asp:Label ID="Label2" runat="server" >Label2</asp:Label>
</contenttemplate>
</asp:UpdatePanel>
</asp:Content>
And my codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
public partial class _Default : Page
{
public int counter = 0;
protected void Timer1_Tick(object sender, EventArgs e)
{
counter++;
System.Diagnostics.Debug.WriteLine("Counter: " + counter);
if (counter == 1)
{
Label1.Text = "<font color='green'>Started</font>";
UpdatePanel1.Update();
}
if (counter == 2)
{
Label2.Text = "<font color='green'>Started</font>";
UpdatePanel1.Update();
}
}
}
After trying several examples I decided to ask here and see if I was missing something obvious. Somehow my counter variable is being reset to 0 which tells me that the entire page may be being rerun each tick instead of just the Timer1_Tick method.
The clause where counter == 1 also increments counter, so by the end of the clause, counter = 2, hence the other condition is also true.
Don't increment counter within the counter == 1 clause.

How I can execute C# code using Roslyn in ASP.Net web form?

I have peice of code in ASP.Net for execute code of C# using roslyn compiler. However, I use ASP.Net web forms to build user interface for execute the code. So,I want to take code from one textbox and by "Compile" button I show the result in another textbox.
So, I have this controls:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>Compiler Tool</h1>
</hgroup>
<p>
You can compile your source code of C# using Roslyn Compiler from Microsoft</p>
<br/>
<p>
<asp:TextBox ID="TextBox3" runat="server" Height="185px" Width="480px" OnTextChanged="TextBox3_TextChanged"></asp:TextBox>
</p>
<p>
<asp:Button ID="Button2" runat="server" onclick="Button_Click" Text="Compile" ForeColor="Black" />
</p>
<p>
<asp:TextBox ID="TextBox2" runat="server" Height="138px" Width="390px" ></asp:TextBox>
</p>
</div>
</section>
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
</asp:Content>
And here the Handler event for it using C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using Roslyn.Scripting;
using Roslyn.Scripting.CSharp;
namespace WebApplication2
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button_Click(object sender, EventArgs e)
{
var engine = new ScriptEngine();
var session = engine.CreateSession();
String code = TextBox3.Text;
session.Execute(code);
}
protected void TextBox3_TextChanged(object sender, EventArgs e)
{
}
}
}
How could I show the result of execution of Code (TextBox3) in TextBox2??
Iam beginner in ASP.Net environment, Any help??
I'm afraid I'm not near a dev pc, so I can't test the code, but here's what comes to mind:
You're not using the result of session.Execute(code);, so if a user were to put in 3+3, it would get executed, and the return value would be 6, but since it's not captured, it simply would go out of scope. If instead, you did object result = session.Execute(code);, the output would be the integer 6; You could then call .ToString() on result and put that in your text box.
And of course be careful allowing users to execute arbitrary code on your webserver...

Page_Load firing twice regardless of what i do

I am working on a simple asp.net login page. Yesterday, the code was working fine. Today, it isn't.
The only thing that changed between yesterday and today is that I shut down my pc and started it again today.
The problem is that Page_Load is firing twice (I checked all the answers/solutions, and none worked (image with empty src, handling the page_load manually, setting autoEventWireUp to false...)) none of these seemed to do the trick.
PLEASE can someone help me figure out why this is happening?
Here is the code for the page and its code behind:
<%# Page Title="Login" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="True" CodeBehind="Login.aspx.cs" Inherits="MatchingWebsite.Login" MaintainScrollPositionOnPostback="true" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1><%: Title %></h1>
</hgroup>
</div>
</section>
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<h2 align="center">Looking for someone to spend your time with? Want to have fun with someone you like?<br />You've come to the right place!!</h2><br /><br /><br />
<img alt="Cupid" src="Images/images.jpg" align="left" />
<img alt="Couple" align="right" src="Images/matchmaking.jpg" /><br /><br />
Username:<br />
<asp:TextBox ID="UserLogIn" runat="server" Width="174px"></asp:TextBox><br /><br />
Password:<br />
<asp:TextBox ID="UserPass" runat="server" Width="175px" TextMode="Password"></asp:TextBox><br />
<asp:Label ID="LoginError" runat="server" Text="Wrong Username/Password Combination. Try again." Visible="False"></asp:Label><br /><br />
<asp:Button ID="LoginButton" runat="server" OnClick="Login_Click" Text="Login" Width="81px" />
<asp:Button ID="NotRegistered" runat="server" Text="Not Registered?" Width="150px" OnClick="Not_Registered" />
</asp:Content>
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="HeadContent">
<style type="text/css">
.auto-style1
{
width: 300px;
height: 113px;
}
</style>
</asp:Content>
And here is the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MatchingWebsite
{
public partial class Login : System.Web.UI.Page
{
Service1 proxy = new Service1();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["username"]!=null && !IsPostBack)
Response.Redirect("~/EnterMyInfo.aspx");
}
protected void Login_Click(object sender, EventArgs e)
{
string user = UserLogIn.Text;
string pass = UserPass.Text;
if (user == "" || pass == "")
System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=\"JavaScript\">alert(\"Username/Password cannot be blank.\")</SCRIPT>");
else
{
if (proxy.login_service(user, pass))
{
Response.Redirect("~/EnterMyInfo.aspx");
}
else
LoginError.Visible = true;
}
}
protected void Not_Registered(object sender, EventArgs e)
{
Response.Redirect("~/SignUp.aspx");
}
}
}
Likely the webpage is really loaded twice. Check your javascripts (or any AJAX components?), or use the browser's debug console to monitor the network requests being sent. Try adding empty methods on the PreInit, PostInit (etc.) events and set breakpoints too, I bet those are hit twice as well.

Invalid postback or callback argument (HiddenField and container Visible=false)

I've not found answers that matched my circumstances, so I'm posting an answered question hoping it will help others.
I was getting the error
Invalid postback or callback argument. Event validation is enabled
using in configuration or <%#
Page EnableEventValidation="true" %> in a page. For security
purposes, this feature verifies that arguments to postback or callback
events originate from the server control that originally rendered
them. If the data is valid and expected, use the
ClientScriptManager.RegisterForEventValidation method in order to
register the postback or callback data for validation.
at System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument)
at System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument)
at System.Web.UI.WebControls.HiddenField.LoadPostData(String postDataKey, NameValueCollection postCollection)
at System.Web.UI.WebControls.HiddenField.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection)
at System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
I've got a Databound ListView (with a few 100s rows), with buttons on each row. The buttons bring a popup. The popup has dropdownlists and other controls doing asynchronous postbacks. I need to make sure I do asynchronous postbacks to avoid refreshing my big table.
I get the error when I click the button on one row, then change a dropdownlist inside the popup which fires a postback (selected item changed). Boom.
Here's the markup for a reduced sample, without popup and javascript at all! It still exhibits the problem. Click twice on a button in a row to get the error.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestPopupAsynchPostback.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="scriptMgr" runat="server" ScriptMode="Debug" EnablePartialRendering="true"
EnableScriptGlobalization="true" EnableScriptLocalization="true" EnablePageMethods="true"/>
<asp:ObjectDataSource ID="ListDataSource" runat="server" SelectMethod="List" TypeName="TestPopupAsynchPostback.Default" />
<asp:Label runat="server" ID="PageLabel"></asp:Label>
<asp:ListView ID="EL" runat="server" DataSourceID="ListDataSource" OnItemDataBound="EntityList_OnItemDataBound">
<LayoutTemplate>
<table border="1">
<tr id="itemPlaceholder" runat="server" enableviewstate="false">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server" id="DefaultRow" enableviewstate="false">
<td>
<asp:Label ID="Lbl" runat="server" EnableViewState="false" />
</td>
<td>
<button runat="server" type="button" id="ReportingButton" enableviewstate="false" onserverclick="ReportingButton_OnClick" causesvalidation="false">click</button>
</td>
</tr>
<%-- Fix part 1: Change SpecialRow visible = true--%>
<tr runat="server" id="SpecialRow" visible="false" enableviewstate="false">
<td>
<asp:Label ID="Lbl2" runat="server" EnableViewState="false" />
<asp:HiddenField runat="server" ID="fn_hid" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
</form>
</body>
</html>
Here's the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace TestPopupAsynchPostback
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager sm = ScriptManager.GetCurrent(Page);
PageLabel.Text = DateTime.UtcNow.ToString() + " IsPostBack:" + IsPostBack + " IsInAsyncPostBack:" + (sm == null ? "" : sm.IsInAsyncPostBack.ToString());
}
protected override void Render(HtmlTextWriter writer)
{
ScriptManager sm = ScriptManager.GetCurrent(this.Page);
if (sm != null)
{
foreach (ListViewDataItem row in EL.Items)
{
HtmlButton reportingButton = row.FindControl("ReportingButton") as HtmlButton;
if (reportingButton != null)
sm.RegisterAsyncPostBackControl(reportingButton);
}
}
base.Render(writer);
}
public IList<string> List()
{
return (new string[] { "ONE", "TWO"}).ToList();
}
protected void ReportingButton_OnClick(object sender, EventArgs e)
{
//Do something useful here, for now, just a postback event
}
protected void EntityList_OnItemDataBound(object sender, ListViewItemEventArgs e)
{
Label lbl = e.Item.FindControl("Lbl") as Label;
Label lbl2 = e.Item.FindControl("Lbl2") as Label;
lbl.Text = lbl2.Text = e.Item.DataItem.ToString();
HtmlTableRow specialRow = e.Item.FindControl("SpecialRow") as HtmlTableRow;
if (e.Item.DataItemIndex%2 == 0)
{
HiddenField fn_hid = e.Item.FindControl("fn_hid") as HiddenField;
fn_hid.Value = "test1";
specialRow.Visible = true;
}
//Fix part 2: set SpecialRow Visible = false in code behind
//else
// specialRow.Visible = false;
}
}
}
I initially thought my javascript was at fault as I am modifying things with it. However, the process of creating a sample page has helped me find the problem.
It turns out it has nothing to do with the javascript or the popup. It's to do with a HiddenField contained inside a TR HtmlControl (asp.net server side control) with Visible=false IN THE MARKUP. I then use the code behind to set Visible=true when I need to in OnItemDataBound event.
This is what is causing the error for me: It seems that because the container (the TR SpecialRow) is Visible=false, I guess something is not rendered. I then come along in OnItemDataBound, decide that this row must be shown, and set Visible=true and set the value of my HiddenField. Boom.
If I remove the markup for the hidden field and don't set its value, no crash.
So it's not just the visibility of the TR on its own, it's the HiddenField too.
My fix: don't set Visible=false in the markup, and change OnItemDataBound to set Visible=false when required.
In other words: I was defaulting to hide things in markup and use code behind to show them. I changed this around and show things by default in markup and hide them using the code behind.
I've added the fix in the markup and code above.

Session data from textbox inputed by user

I have this project where I want to transfer data from textbox1 with session "sam" on the about.aspx on its label. The problem is that when I input a number, it is not shown on label. My problem is that I type something on the "Αριθμός Επιβατών:" textbox (a number for example) and after that I click submit I need to get the number on the about page next to "Ari8mos epivatwn :"
Defaultaspxcs.txt:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication4
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click2(object sender, EventArgs e)
{
string txt = TextBox1.Text;
Session["sam"] = txt;
}
}
}
Aboutaspxcs.txt:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication4
{
public partial class About : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = (string)Session["sam"];
}
}
}
Aboutaspx.txt:
<%# Page Title="About Us" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="About.aspx.cs" Inherits="WebApplication4.About" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<p>
Ari8mos epivatwn :
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</p>
</asp:Content>
https://www.dropbox.com/sh/4ftlddfhqo8n99p/gm-TNvol0S
It's likely that the content for the Label is being written twice, and not in the order your expect.
Start by familiarizing yourself with the asp.net page life-cycle
You will notice that PageLoad is called long before Render.
So, the page loads like this:
PageLoad Label text set to some number from your code
A bunch of other stuff
Render sets the Label text to "Label" instead, since that is what you have defined in your chtml.
Review this part of your code:
...
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
...
Try this instead:
...
<asp:Label ID="Label1" runat="server"></asp:Label>
...

Categories

Resources