I cant access <asp:textbox> value in code behind file - javascript

Good Morning
I have a webpage with a button pad on it. It is used at a gas station with bad network so everytime they click on the button to add a number to the textbox it will load forever so I changed the button clicks to javascript.
It works perfectly but now the code behind gets an empty value (Not null) when i retrieve the value from the textbox.
This is my code
The buttons used to add the numbers to the textbox
and the textbox
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="OVKWEBAPP.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" type="text/css" href="mainstyle.css" />
<style type="text/css">
.modal
{
position: fixed;
top: 0;
left: 0;
/*background-color: black;*/
z-index: 99;
opacity: 0.8;
filter: alpha(opacity=80);
-moz-opacity: 0.8;
min-height: 100%;
width: 100%;
}
.loading
{
font-family: Arial;
font-size: 10pt;
border: 5px solid #67CFF5;
width: 200px;
height: 100px;
display: none;
position: fixed;
background-color: White;
z-index: 999;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtRknr" runat="server" CssClass="txtBoxRknr" PlaceHolder="Rekening Nommer" Enabled="False" autocomplete="off" Width="175px"></asp:TextBox>
<input type="button" id="btnPad1" runat="server" value="1" class="buttonsb" onclick="input(this);"/>
<input type="button" id="btnPad2" runat="server" value="2" class="buttonsb" onclick="input(this);"/>
<asp:Button ID="btnMsg1" runat="server" Text="Gaan Voort" CssClass="buttonsa" OnClick="btnMsg1_Click" />
</form>
</body>
<script type="text/javascript">
function input(e) {
document.getElementById("<%=txtRknr.ClientID %>").value = document.getElementById("<%=txtRknr.ClientID %>").value + e.value;
}
</script>
</html>
And this is my code in the code behind file
protected void btnMsg1_Click(object sender, EventArgs e)
{
lblError.Text = "";
//string user = txtRknr.Text;
string user = ((TextBox)FindControl("txtRknr")).Text;
if(user == "")
//if (txtRknr.Text == "")
{
lblError.Text = "ONGELDIGE REKENING NOMMER";
return;
}
}
Basically all this needs to do is add an account number to a textbox from an button pad on the website.
After the account is added they would click on continue button and then the code behind checks if the textbox is empty if it is not empty it connects to database to check if it is valid.
But no matter how many numbers i add to the textbox it is still empty when i access it from code behind.

Enabled="False" means that your input field will have a disabled attribute. Disabled form elements do not get posted in HTML forms, which means that when you access it from the code-behind, it's using the default value of the textbox.
Try ReadOnly="True" instead of Enabled="False" if you don't want the field to be edited by hand.
EDIT
I guess ASP.NET prevents you from reading the value from a ReadOnly=True textbox, to prevent you from doing exactly what you're trying to do. A <asp:HiddenField> creates an <input type="hidden">, which you should be able to write the value and have it posted properly to the codebehind.

In the line
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="OVKWEBAPP.WebForm1" %>
replace in Inherits="OVKWEBAPP.WebForm1" with Inherits="OVKWEBAPP.default"

try this.
Request.Form["by-name-attribute"];

Related

Preserving line breaks from text-area when sending mail

I'm trying to make a website where you can write and customize a mail then send it. I have a problem where the line breaks from a text-area doesn't preserve. When I send the mail with c#, there are no line breaks (sorry for my bad English, not my first language).
Here's my code:
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Web_Mail_Manager
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string YourUsername = "(Just gonna cover my Email)";
string YourPassword = "(Just gonna cover my password)";
string Destination = DestinationAdress.Value;
string YourMessageSubject = MailSubject.Value;
string YourMessageBody = MailBody.Value;
try
{
using (SmtpClient client = new SmtpClient("smtp.gmail.com", 587))
{
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(YourUsername, YourPassword);
System.Net.Mail.MailMessage msgObj = new System.Net.Mail.MailMessage();
msgObj.To.Add(Destination);
msgObj.From = new MailAddress(YourUsername);
msgObj.Subject = YourMessageSubject;
msgObj.Body = YourMessageBody;
msgObj.IsBodyHtml = true;
client.Send(msgObj);
}
}
catch (Exception)
{
}
}
}
}
ASPX:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Web_Mail_Manager.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet" />
<style>
body {
background-color: lightgray;
font-family: 'Poppins', sans-serif;
}
.mailPreview {
background-color: white;
position: absolute;
top: 10%;
left: 50%;
transform: translate(-50%);
width: 45vw;
height: fit-content;
padding: 15px;
}
#MailBody {
white-space: pre-wrap;
}
#MailbodyContent {
white-space: pre-line;
}
#MailBody {
white-space: pre-line;
}
</style>
<script>
function changeTo(val) {
document.getElementById("toMail").innerHTML = val;
}
function changeSubject(val) {
document.getElementById("subject").innerHTML = val;
}
function changeBody(val) {
var text = val;
document.getElementById("MailbodyContent").textContent = text;
document.getElementById("MailbodyContent").innerHTML.replace(/\n/g, '<br>\n');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<input id="DestinationAdress" oninput="changeTo(value)" runat="server" type="text" placeholder="Recievers E-mail adress" /><br />
<input id="MailSubject" oninput="changeSubject(value)" runat="server" type="text" placeholder="Subject" /><br />
<textarea id="MailBody" oninput="changeBody(value)" runat="server" cols="40" rows="5" placeholder="Content"></textarea><br />
<br />
<div class="mailPreview" id="mailPreview">
<h3>To: <span id="toMail"></span></h3>
<h3>From: (Just gonna cover my email)</h3>
<br />
<h3>Subject: <span id="subject"></span></h3>
<br />
<h3>Content:</h3>
<h4 runat="server" id="MailbodyContent"></h4>
<asp:HiddenField ID="HiddenField1" runat="server" />
</div>
<asp:Button ID="Button1" runat="server" Text="Send mail!" OnClick="Button1_Click" />
</form>
</body>
</html>
Any help would be greatly appriciated!
Since you are sending HTML E-Mails (msgObj.IsBodyHtml = true;) you need to replace newlines with the <br /> tag.
Replace the line
string YourMessageBody = MailBody.Value;
with
string YourMessageBody = MailBody.Value.Replace(Environment.NewLine, "<br />");

Display a django-from from JS

so here is the thing i have a block of html code that needs to be replaced when a button is clicked. Its no big deal using
$('div.myCustomReplacer').replaceWith(newHTML);
but i also need to render a django-form {{ form }} in the new HTML
when i simply use
<div class="NewDiv"> {{ form }} </div? the html is rendered as "{{ form }}" because of those quotes the form is not rendered.
So how i do remove those ?
sorry just new to JavaScript.
I don't think you can achieve it like that. Remember that the form is added when html is rendered in the server, so basically {{form}} doesn't exist in client.
No worries, there are several simple ways to reach you goal just using simple JavaScript. One way is to simple let server inject the form, and just make it visible when user click button. Take a look at the example I made for you.
document.getElementById('showBtn')
.addEventListener('click', function () {
document.getElementById('targetDiv').style.display = 'block';
});
document.getElementById('hideBtn')
.addEventListener('click', function () {
document.getElementById('targetDiv').style.display = 'none';
});
html, body {
width: 100%;
height: 100%;
font-family: 'Roboto', sans-serif;
}
button {
margin: 1rem;
}
section {
margin: 1rem;
}
section span {
background-color: lightcoral;
font-size: small;
padding: .5rem;
}
<!doctype html>
<html lang="en">
<head>
<title>Hide Form</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
<link href="./style.css" rel="stylesheet">
</head>
<body>
<button id="showBtn">Show Form</button>
<button id="hideBtn">Hide Form</button>
<section>
<div id="targetDiv" style="display: none;">
<h2>Form <span> (a moment ago I was just hidden)</span></h2>
<form>
<label for="someInput">Bla bla</label>
<input id="someInput" type="text"/>
</form>
</div>
</section>
<script src="./app.js"></script>
</body>
</html>

Show and Hide Progress Bar in Page_Load

I have implemented some web-page in ASP.NET. I want to add a progress bar to my page. Because the page takes several minutes to load.
I want to put show Progress bar function at the start of Page_Load function. And hide it at the end of the Page_Load function. How can I implement this?
Please give me some advice. Thank you in advance.
<%# Page Language="C#" AutoEventWireup="true" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script type="text/javascript" src="Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<style type="text/css">
#loading
{
font-family: Arial;
font-size: 10pt;
border: 5px solid #67CFF5;
width: 220px;
height: 20px;
display: none;
position: fixed;
background-color: White;
z-index: 999;
text-align: center;
line-height: 20px;
}
</style>
<script type="text/javascript">
function ToggleProgressBar() {
var loading = window.jQuery('#loading');
if (loading.is(':visible')) {
loading.hide();
}
else {
var top = Math.max(parseInt($(window).height() / 2 - loading.height() / 2), 0);
var left = Math.max(parseInt($(window).width() / 2 - loading.width() / 2), 0);
loading.css({ top: top, left: left });
loading.show();
}
}
function blahblah(s, e) {
// some blah blah function contents
}
function blahblah2(s, e) {
// some blah blah function contents
}
</script>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
**// TODO: Show Progress Bar**
DelayTime(); // dummy function to delay page load
**// TODO: Hide Progress Bar**
}
protected void DelayTime()
{
txt_delay.InnerText = "";
for (int i = 0; i < 3000; i++)
{
txt_delay.InnerHtml += i.ToString("0000") + ", ";
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<span id="txt_delay" runat="server"></span>
<div id="loading" align="center" runat="server">
Loading...
<%--<img src="/Images/progress-indicator.gif" alt="" />--%>
</div>
</div>
</form>
</body>
</html>
Another way would be to give your css a class. Then put a div as a placeholder where you want the window to show. Give the div an id and assign it's css class the id of your class and set the display attribute to none. Then when you are ready use a bit of jquery to change the display from none to say block. assuming you have done something like div id='myWait' display='none' class='mycssclass'
then jquery along the lines ('#myWait').attr('display','block');

How to reference JavaScript code in MasterPage from within another aspx page

Simple question: How do I refer to JavaScript code on a Master page file, (which is also on the same folder as many other ASPX pages), from one of my ASPX pages?
Master Page
<%# Master Language="C#" AutoEventWireup="true" CodeFile="JobRegister.master.cs" Inherits="JobRegister_Job" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Tec-NQ miJob Register</title>
<style type="text/css">
textarea { font-family: Arial; font-size: 10pt; }
a { white-space: nowrap; }
.tablestyle { background-color:#eeeeee; width:100%; margin-bottom:2px; padding:3px; }
.checkboxlist input { position:relative; left: 360px; }
.checkboxlist label { position:relative; left: -22px; }
.hidepanel { display: none; }
.showpanel { display: block; }
</style>
<script src="<%# ResolveUrl("~/") %>" type="text/javascript">
/*
Added : Variables required for image uploading & validation checking.
By : Amit Champaneri
On : 4th April 2008
*/
var hoverColor = "#00000b"; //DIV Color when mouse is hover the DIV
var defaultColor = "black"; //DIV default color
var selectColor = "#000000"; // DIV color when its selected.
var selectedDIV = ""; //ID of the DIV user has currently selected(it will be 1,2,3 or 4)
var objActiveX; //Object of Clipboard ActiveX control.
..
..etc..
My ASPX page has a reference to the Javascripts in the Master Page ...
ASPX page
<%# Page Language="C#" MasterPageFile="~/JobRegister/JobRegister.master" AutoEventWireup="true" CodeFile="Details.aspx.cs" Inherits="JobRegister_Details" %>
<%# Register TagPrefix="tecnq" TagName="JobAction" Src="ActionControl.ascx" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:FormView ID="FormView1" runat="server" DataSourceID="SqlDataSource1" DataKeyNames="JobID, CreatedBy" GridLines="None"
AllowPaging="True" DefaultMode="Edit" OnDataBound="FormView1_OnDataBound" OnItemCreated="FormView1_OnItemCreated"
OnItemUpdated="FormView1_OnItemUpdated" OnItemUpdating="FormView1_Updating"
HeaderText="Job Details" CellPadding="0" Font-Names="Arial" Font-Size="10pt">
<HeaderStyle BackColor="#5D7B9D" ForeColor="White" Font-Bold="True" HorizontalAlign="Center" Height="30px" />
<InsertItemTemplate>
...
..etc..
...
<img id="imgPaste1" src="Images/imgPaste.gif" class="LinkImage" title="Click here to Paste any copied Image" onclick="javascript:pasteOnClick('1');" />
..
..etc..
..
I got all this from a great blog on how to paste clipboard IMAGEs into a web form ...
http://www.codeproject.com/Articles/25967/Clipboard-ActiveX-for-Image-Copy-Paste-into-Web-Fo
The demo in the above blog works great, but both the Javascript and the ASPX code are all inside the same file!
How can I do the same with the Javascript in the MasterPage and have references to the scripts in my ASPx file?
I tried also to place all the code inside just my ASPX file but I get an invalid reference error on this line of code ...
document.getElementById("<%=hdnImageFileName1.ClientID %>").value = "";
It's saying it cannot find a reference to "hdnImageFileName1", but I know it's in my ASPX page further down ...
ie
<asp:HiddenField runat="server" ID="hdnImageFileName1" />
Thanks in advance.
The answer was like #deostroll said. I moved all my JS code into a custom.js file and referenced it simply via markup. Simple. Done! Thank you

Floating feedback form in asp.net

I am displaying a floating feedback form in my website and using JQuery to handle the slide in and out functionality. Following is the code.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SlidingWindow.Default" %>
<%# Register TagPrefix="ajax" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>
<form id="form1" runat="server">
<asp:ScriptManager runat = "server"></asp:ScriptManager>
<div class="feedback-panel">
<asp:UpdatePanel ID="UpdatePanel1" runat = "server">
<ContentTemplate>
<a class="feedback-tab" href="#"></a>
<asp:Panel ID = "panel1" runat = "server">
<table>
<tr style="height:100%;white-space:nowrap;"><td><asp:Label ID="Label1" runat = "server" Text = "Name"></asp:Label></td></tr>
<tr style="height:100%;white-space:nowrap;"><td><asp:TextBox runat = "server" ID = "txtName" CssClass = "feedbacktextbox"></asp:TextBox></td></tr>
<tr style="height:100%;white-space:nowrap;"><td><asp:Label ID="lblEmail" runat = "server" Text = "Email"></asp:Label></td></tr>
<tr style="height:100%;white-space:nowrap;"><td><asp:TextBox runat = "server" ID = "txtEmail" CssClass = "feedbacktextbox"></asp:TextBox></td></tr>
<tr style="height:100%;white-space:nowrap;"><td><asp:Label ID="lblFeedback" runat = "server" Text = "Comments"></asp:Label></td></tr>
<tr style="height:100%;white-space:nowrap;"><td><asp:TextBox runat = "server" ID = "txtFeedback" TextMode="MultiLine" CssClass = "width"></asp:TextBox></td></tr>
<tr style="height:100%;white-space:nowrap;"><td><asp:Button runat = "server"
ID = "btnFeedbackSubmit" Text = "Submit" onclick="btnFeedbackSubmit_Click" />
</td></tr>
</table>
</asp:Panel>
<asp:Panel ID = "panel2" runat = "server"><asp:Label runat = "server" ID = "lblFeedbackMsg"></asp:Label></asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
<script type="text/javascript">
$(document).ready(function () {
var feedbackTab = {
speed: 300,
containerWidth: $('.feedback-panel').outerWidth(),
containerHeight: $('.feedback-panel').outerHeight(),
tabWidth: $('.feedback-tab').outerWidth(),
init: function () {
$('.feedback-panel').css('height', feedbackTab.containerHeight + 'px');
$('a.feedback-tab').click(function (event) {
if ($('.feedback-panel').hasClass('open')) {
$('.feedback-panel')
.animate({ left: '-' + feedbackTab.containerWidth }, feedbackTab.speed)
.removeClass('open');
} else {
$('.feedback-panel')
.animate({ left: '0' }, feedbackTab.speed)
.addClass('open');
}
//event.preventDefault();
});
}
};
feedbackTab.init();
});
</script>
<style type="text/css">
.feedback-panel {
padding:5px;
width: 250px;
background:#C4C4FF;
border: 5 solid #8080FF;
font-family: Arial, Helvetica, Sans-Serif;
font-size: 12px;
color: White;
position:fixed;
top:77px;
left:-261px;
}
.feedback-panel a.feedback-tab {
background: url(/images/feedbackbutton.gif) no-repeat scroll 0 0;
display:block;
height:122px;
left:45px;
bottom:5px;
position:relative;
float:right;
text-indent:-9999px;
width:40px;
outline:none;
}
.feedbackformtable
{
width: 215px;
}
.feedbacklabel
{
font-family: Arial Helvetica Sans-Serif;
font-size: medium;
color: Black;
}
.feedbacktextbox
{
width: 200px;
font-family: Verdana;
font-size: 12px;
border: 1px solid #8080FF;
}
</style>
The form is used to send feedback as an email. As soon as the submit button is clicked, the form is closed. Is there any way to keep the form open after clicking the submit button? I want to display a message on the form instead of closing it. Much appreciate any help.
Thanks.

Categories

Resources