Why is the textbox in my ASP.NET webform always empty - c#

This is my markup:
<%# Page Title="" Language="C#" MasterPageFile="~/User/Default.Master" AutoEventWireup="true" CodeBehind="Consulation.aspx.cs" Inherits="PetShop.User.Consulation" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script>
window.onload = function () {
var second = 5;
setTimeout(function () {
document.getElementById("<%=lblMsg.ClientID%>").style.display = "none";
}, second * 1000)
}
</script>
<link href="../CSSandJS/StyleCss/consulation.css" rel="stylesheet" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<!-- Slider -->
<section id="Slider">
<div class="aspect-ratio-169">
<img src="../CSSandJS/images/bg_1.jpg" alt="">
<img src="../CSSandJS/images/bg_2.jpg" alt="">
<img src="../CSSandJS/images/bg_3.jpg" alt="">
<img src="../CSSandJS/images/bg_4.jpg" alt="">
</div>
<div class="dot-container">
<div class="dot active"></div>
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
</div>
</section>
<!-- End Slider -->
<!-- Free Consulation -->
<section class="contact">
<div class="container-contact">
<h1>Đặt lịch hẹn</h1>
<div class="row">
<div class="contact-img">
<img src="../CSSandJS/images/bg_1.jpg" alt="" width="400">
</div>
<div class="input-infor">
<div class="form">
<div class="dbl-field">
<asp:DropDownList ID="ddlCategory" runat="server" CssClass="form-control option field-mail listOp" DataSourceID="SqlDataSource1" DataTextField="TENDV" DataValueField="MADV" AppendDataBoundItems="true">
<asp:ListItem Value="0">Chọn danh mục</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:cs %>" SelectCommand="SELECT [MADV], [TENDV] FROM [DICHVU]"></asp:SqlDataSource>
</div>
<div class="dbl-field">
<div class="field-mail">
<asp:TextBox ID="txtEmail" runat="server" CssClass="form-control input" placeholder="Nhập email" required></asp:TextBox>
<i class="ri-mail-line"></i>
</div>
</div>
<div class="dbl-field">
<div class="field">
<asp:TextBox ID="txtNameAcc" runat="server" CssClass="form-control input" placeholder="Nhập tên"></asp:TextBox>
<i class="ri-user-line"></i>
</div>
<div class="field">
<asp:TextBox ID="txtSDT" runat="server" CssClass="form-control input" placeholder="Nhập số điện thoại" MaxLength="11"></asp:TextBox>
<i class="ri-phone-line"></i>
</div>
</div>
<div class="dbl-field">
<div class="field">
<asp:TextBox ID="txtNgay" runat="server" CssClass="form-control input" TextMode="Date"></asp:TextBox>
<i class="ri-calendar-2-line"></i>
</div>
<div class="field">
<asp:TextBox ID="txtTime" runat="server" CssClass="form-control input" placeholder="Nhập giờ hẹn" MaxLength="5" TextMode="SingleLine"></asp:TextBox>
<i class="ri-time-line"></i>
</div>
</div>
<div class="message">
<asp:TextBox ID="txtDescription" runat="server" CssClass="form-control textarea" placeholder="Tin nhắn" TextMode="MultiLine"></asp:TextBox>
<i class="ri-message-2-line"></i>
</div>
<div class="button-area">
<asp:Button ID="Add" runat="server" Text="Gửi lịch hẹn" class="btn btn-primary button" OnClick="Add_Click"/>
<asp:Label ID="lblMsg" runat="server" Visible="false"></asp:Label>
<%--<asp:linkbutton id="submitcal" runat="server" cssclass="btn btn-primary button" OnClick="Add_Click">gửi lịch hẹn</asp:linkbutton>--%>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- End Free Consulation -->
</asp:Content>
The textbox doesn't get any value when I debug the program.
I have tested the stored procedure in SQL Server and it works fine. But the data returned from the SQL code is empty.
My button submit code:
namespace PetShop.User
{
public partial class Consulation : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
}
private void clear()
{
txtEmail.Text = string.Empty;
txtDescription.Text = string.Empty;
txtNameAcc.Text = string.Empty;
txtSDT.Text = string.Empty;
txtNgay.Text = string.Empty;
txtTime.Text = string.Empty;
ddlCategory.ClearSelection();
}
protected void Add_Click(object sender, EventArgs e)
{
string actionName = string.Empty;
bool isValidToExcute = true;
con = new SqlConnection(Connection.GetConnectionString());
cmd = new SqlCommand("Add_KHaddLH", con);
cmd.Parameters.AddWithValue("#Action", "INSERT4KH");
cmd.Parameters.AddWithValue("#MaDv", ddlCategory.SelectedValue);
cmd.Parameters.AddWithValue("#EMail", txtEmail.Text.Trim());
cmd.Parameters.AddWithValue("#Ten", txtNameAcc.Text.Trim());
cmd.Parameters.AddWithValue("#Sdt", txtSDT.Text.Trim());
cmd.Parameters.AddWithValue("#NgayHen", txtNgay.Text.ToString());
cmd.Parameters.AddWithValue("#GioHen", txtTime.Text.Trim());
cmd.Parameters.AddWithValue("#GhiC", txtDescription.Text.Trim());
if (isValidToExcute)
{
cmd.CommandType = CommandType.StoredProcedure;
try
{
con.Open();
cmd.ExecuteNonQuery();
actionName = "gửi";
lblMsg.Visible = true;
lblMsg.Text = "Lịch hẹn " + actionName + " thành công!";
lblMsg.CssClass = "alert alert-success";
clear();
}
catch (Exception ex)
{
lblMsg.Visible = true;
lblMsg.Text = "Lỗi !!!" + ex.Message;
lblMsg.CssClass = "alert alert-danger";
}
finally
{
con.Close();
}
}
}
}
}
I think the error lies in the page reload, because when submitting it will delete all the data in the textbox and then enter.
I've tried adding some commands to the button but still can't handle that it keeps losing textbox data.
I update code behind and markup.
Support me,
Thank.

Ok, so that helps a boatload.
if we have this code:
protected void Add_Click(object sender, EventArgs e)
{
string actionName = string.Empty;
bool isValidToExcute = true;
Debug.Print(txtEmail.Text);
output:
So, you might want to put a break point in, or simple add some debug.prints, and see which text box controls are "empty". But, just looking at what you have, those text boxes should be ok.
And including page-load, shows that you not say running the "clear" routine you have. (so, having included the page load event eliminates about 100 possible issues here. This is VERY much why posting some of your code allows the public here to eliminate a 100 "back and forth" suggestions.) So, for example, had you included "clear" routine in page load, then of course page load fires each and every time BEFORE a button click event, so code in page load is VERY OFTEN suspect here. But, since you don't have code in page load event, we scratch that off the table.
So, far, the controls look to have values, but I suggest you add a break point, or some debug.prints as per above to be 100% sure that the controls in fact do not have values.
Also, just pasting in some of the markup, we see things like this:
So, you do have stray "garbage" in a number of places. (not good).
As it stands, with the posted markup, I MOST certainly do get/see/have/enjoy/observe that the text boxes are intact, do have values.
Given we can't re-produce your issue?
I suggest creating a blank new page, drop in some of those controls, and try a test button - (don't even bother with the database save code - we NOT gone that far down the debugging road just yet).
So, only thing so far?
Are you 100% sure the text boxes don't have values, and you tested this BEFORE any of the database save code runs?
and do remove the stray "required" markup in that txtEmail box, the editor even HONKS OUT AT YOU that the markup is bad as per above screen shot.
In fact, drop in another button on the form, and its only job would be to debug print out the text boxes - does that work?
As it stands now, you don't have a re-producable error, and the community in general here has not, does not see your error, nor are we the viewing public EVEN able to re-produce that these text boxes don't have values.
As a result, there information we don't have to re-produce the error.
I suggest building a page with just the txtEmail that is blank, and a simple button. if that works, then start adding markup from that other page until it stops working, since we here can't re-produce your issue with the provided code and markup you have provided.
And, since you using a master page, then check if page load in master page has any code that runs on page load.

Related

Maintain collapse state on postback ASP.NET

I have two different forms that collapse and show either one or the other and there's a button to control them.
<div>
<button type="button"
data-toggle="collapse"
data-target=".multi-collapse"
aria-expanded="false"
aria-controls="form1 form2"> Change Form
</button>
<div class="collapse multi-collapse show" id="form1">
<asp:DropDownList AutoPostBack="true"
OnSelectedIndexChanged="SetDdl2ValuesBasedOnWhatIsSelectedOnDdl1"
ID="Ddl1"
runat="server">
</asp:DropDownList>
<asp:DropDownList ID="Ddl2"
runat="server">
</asp:DropDownList>
<asp:Button ID="Button1" OnClick="SubmitBtn"
<\div>
<div class="collapse multi-collapse" id="form2">
<asp:DropDownList AutoPostBack="true"
OnSelectedIndexChanged="SetDdl2ValuesBasedOnWhatIsSelectedOnDdl1"
ID="Ddl1"
runat="server">
</asp:DropDownList>
<asp:DropDownList ID="Ddl2"
runat="server">
</asp:DropDownList>
<asp:Button ID="Button1" OnClick="SubmitBtn"
<\div>
</div>
My problem is that whenever theres a post back I lose the collapse state of the forms and it goes back to the form1 showing and form2 hiding.
I want to save the state of the collapsables so they stay the same after a postback and I don't know how to do it.
I have done this through PageRequestManager, of course preserving the state of one or two divs, in your case there are two but if there are more, the solution I give is quite difficult but functional:
ASPX Code:
Add your controls in UpdatePanel
<div>
<button type="button"
data-toggle="collapse"
data-target=".multi-collapse"
aria-expanded="false"
aria-controls="form1 form2"> Change Form
</button>
<asp:UpdatePanel ID="up" runat="server">
<ContentTemplate>
<div class="collapse multi-collapse show" id="form1">
<asp:DropDownList AutoPostBack="true"
OnSelectedIndexChanged="Ddl1_SelectedIndexChanged"
ID="Ddl1"
runat="server">
</asp:DropDownList>
<asp:DropDownList ID="Ddl2"
runat="server">
</asp:DropDownList>
<asp:Button runat="server" ID="Button1" OnClick="Button1_Click" Text="btn1" />
</div>
<div class="collapse multi-collapse" id="form2">
<asp:DropDownList AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
ID="DropDownList1"
runat="server">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2"
runat="server">
</asp:DropDownList>
<asp:Button runat="server" ID="Button2" OnClick="Button1_Click1" Text="btn2" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
JavaScript Code:
The event add_beginRequest is an event that is fired when a Postback starts and it is possible to save the DOM state, while add_endRequest is the event that is fired when the panel is updated and the Postback ends, this is where the controls are arranged according to the conditions:
<script type="text/javascript">
var statusForm1 = false,
statusForm2 = false;
var prm = Sys.WebForms.PageRequestManager.getInstance();
function EndRequestHandler(sender, args) {
if (statusForm1) {
$('#form1').collapse('show');
}
if (statusForm2) {
$('#form2').collapse('show');
}
}
function BeginRequestHandler(sender, args) {
statusForm1 = $('#form1').is(":visible");
statusForm2 = $('#form2').is(":visible");
}
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
</script>
There is a simple and straight forward way of doing this which is, adding the class show to the div that you want to actually show. So, in order to do it, you must set both the divs to run at server. Here is my proposed idea for this problem:
<div class="collapse multi-collapse show" id="myform1" runat="server">
<!-- because in aspx, there is already a form1 form which is parent of all elements that runs at server -->
<!-- Other elements go here -->
</div>
<div class="collapse multi-collapse" id="myform2" runat="server">
<!-- Other elements go here -->
</div>
And on server events, you need to hide and show the respective divs by adding the classes to them.
protected void SubmitBtn1(object sender, EventArgs e)
{
// DoStuff();
ShowMyForm1();
}
protected void SubmitBtn2(object sender, EventArgs e)
{
// DoStuff();
ShowMyForm2();
}
protected void SetDdl2ValuesBasedOnWhatIsSelectedOnDdl1(object sender, EventArgs e)
{
// DoStuff();
// I assume this dropdown is in second form div.
ShowMyForm2();
}
private void ShowMyForm1()
{
myform1.Attributes["class"] = "collapse multi-collapse show"; // this will show the div
myform2.Attributes["class"] = "collapse multi-collapse"; // this will hide the div.
}
private void ShowMyForm2()
{
myform1.Attributes["class"] = "collapse multi-collapse"; // this will hide the div
myform2.Attributes["class"] = "collapse multi-collapse show"; // this will show the div
}
Notice, I have given two events for your submit button because it was appearing on both the forms and it had the same ID for it, which is not allowed for server controls. An ID must be unique. And your form2 has all the elements duplicated in it from the form1
So, to differentiate between those elements, You will have to give them different IDs.

How to redirect to another page after a delay

I have a sign-in box in my webpage which is inside an UpdatePanel
<asp:UpdatePanel runat="server" ClientIDMode="Static" ID="upSign" UpdateMode="Conditional">
<ContentTemplate>
<div class="dvHolder hidOverflow clearfix">
<input id="txtSUser" type="text" name="SUsername" value="" placeholder="Username" runat="server" />
</div>
<div class="dvHolder hidOverflow clearfix">
<input id="txtSPass" type="password" name="SPassword" value="" placeholder="Password" runat="server" />
</div>
<div class="dvHolder hidOverflow clearfix setTextRight">
<asp:Button ID="btnSignIn" ClientIDMode="Static" runat="server" Text="Sign In" OnClick="btnSignIn_Click" />
<asp:Label runat="server" Text="" ID="lblSSuccess" ClientIDMode="Static" CssClass="lblMsgSuccess" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
Once the user is validated successfully, I want to show a message and redirect after a delay (let's say 5 seconds). I have the following code but it is not redirecting:
public void btnSignIn_Click(object sender, EventArgs e)
{
lblSSuccess.Text = "We found you, now redirecting...";
lblSSuccess.ForeColor = ColorTranslator.FromHtml("#037203");
Session["UseIsAuthenticated"] = "true";
Response.AppendHeader("Refresh", "5;url=homepage.aspx");
}
The message is updated but the page is not redirecting for some reason.
Please help me resolve the issue.
You can write a block of Javascript with a delay and redirect to the page with this code
public void btnSignIn_Click(object sender, EventArgs e)
{
lblSSuccess.Text = "We found you, now redirecting...";
lblSSuccess.ForeColor = ColorTranslator.FromHtml("#037203");
Session["UseIsAuthenticated"] = "true";
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "redirectJS",
"setTimeout(function() { window.location.replace('homepage.aspx') }, 5000);", true);
}
There are many ways to do this but I love to use this code because it works well when used in many different circumstances. This is with a 5 second delay.
HtmlMeta oScript = new HtmlMeta();
oScript.Attributes.Add("http-equiv", "REFRESH");
oScript.Attributes.Add("content", "5; url='http://www.myurl.com/'");
Page.Header.Controls.Add(oScript);
first create a function that makes the action you need (redirect to page for example)
Second add timer to your markup and set the time interval to 5000 ( 5 sec) and mark the timer as enabled=false so the timer wont start after the page loading
once the user is validated successfully, show the message you want then enable the timer
Response.AppendHeader("Refresh", "2;url=page.aspx");

Control 'MainContent_forenameTxt' of type 'TextBox' must be placed inside a form tag with runat=server

Control 'MainContent_forenameTxt' of type 'TextBox' must be placed inside a form tag with runat=server. [And similar errors]
This error has been bugging me for a few days now. I've narrowed the problem down to an issue being within my Master Page.
For some reason, ASP TextBoxes, Buttons etc.. require to be in a form (Which shouldn't necessarily be the case) however my Program decided that it wants to be.
So, this issue began when I placed the forms in, stating I could only have one with a runat="server". After much googling and questioning I was given this piece of code:
public override void VerifyRenderingInServerForm(Control Control)
{
//base.VerifyRenderingInServerForm(Control);
}
Which, from what I can see, does absolutely nothing. It never gets called, and has nothing in it, however makes the page display - so I have absolutely no idea what it does.
So continuing on, it began to bug me, then I realised that my Buttons weren't actually doing anything, except 'refreshing' the page essentially. (Refer to near the bottom of page, with the onClicks
<%# Page Title="Registration" Language="C#" AutoEventWireup="true" MasterPageFile="~/MasterPage.Master" CodeFile="registration.aspx.cs" Inherits="registration" %>
<div class="contact-bg2">
<div class="container">
<div class="booking">
<h3>Register</h3>
<p>
</p>
<div class="col-md-8 booking-form">
<h5>Forename</h5>
<asp:TextBox ID="forenameTxt" runat="server"></asp:TextBox>
<h5>Surname</h5>
<asp:TextBox ID="surnameTxt" runat="server"></asp:TextBox>
<h5>Telephone</h5>
<asp:TextBox ID="telephoneTxt" runat="server"></asp:TextBox>
<h5>Mobile</h5>
<asp:TextBox ID="mobileTxt" runat="server"></asp:TextBox>
<h5>Address</h5>
<asp:TextBox ID="addressLn1Txt" placeholder="Line 1" runat="server"></asp:TextBox>
<asp:TextBox ID="addressLn2Txt" placeholder="Line 2" runat="server"></asp:TextBox>
<asp:TextBox ID="addressLn3Txt" runat="server" placeholder="Line 3"></asp:TextBox>
<h5>Postal Code</h5>
<asp:TextBox ID="postalTxt" runat="server"></asp:TextBox>
<h5>Username</h5>
<asp:TextBox ID="registerUsernameTxtbox" runat="server"></asp:TextBox>
<h5>Password Confirm Password</h5>
<asp:TextBox ID="registerPasswordTxtbox" runat="server" type="password"></asp:TextBox>
<asp:TextBox ID="passwordConfirmTxt" runat="server" type="password"></asp:TextBox>
<h5></h5>
<asp:Button ID="submitBtn" runat="server" Text="SUBMIT" OnClick="submitBtn_Click" />
<asp:Button ID="resetBtn" runat="server" Text="RESET" OnClick="resetBtn_Click" />
</div>
</div>
</div>
</asp:Content>
Code Behind:
protected void submitBtn_Click(object sender, EventArgs e)
{
//If there is any blank fields, these if statements will be run.
try
{
//If the fields entered have all had an input, this if statement will submit it to the database.
if (forenameTxt.Text != "" && surnameTxt.Text != "" && telephoneTxt.Text != "" && addressLn1Txt.Text != "" && addressLn2Txt.Text != "" && postalTxt.Text != "" && registerUsernameTxtbox.Text != "" && registerPasswordTxtbox.Text != "" && passwordConfirmTxt.Text != "")
{
DLQueries reposit = new DLQueries();
//Refers to 'addCustomerAccount' in droversLodgeRepository
reposit.addCustomerAccount(registerUsernameTxtbox.Text.ToString(),
registerPasswordTxtbox.Text.ToString(), forenameTxt.Text.ToString(),
surnameTxt.Text.ToString(), mobileTxt.Text.ToString(), telephoneTxt.Text.ToString(),
addressLn1Txt.Text.ToString(), addressLn2Txt.Text.ToString(),
addressLn3Txt.Text.ToString(), postalTxt.Text.ToString());
//Redirects to homepage
}
else
{
Response.Redirect("homepage.aspx");
}
}
catch (Exception)
{
}
}
protected void resetBtn_Click(object sender, EventArgs e)
{
forenameTxt.Text = "";
surnameTxt.Text = "";
telephoneTxt.Text = "";
addressLn1Txt.Text = "";
addressLn2Txt.Text = "";
postalTxt.Text = "";
registerUsernameTxtbox.Text = "";
registerPasswordTxtbox.Text = "";
passwordConfirmTxt.Text = "";
}
Now from that alone, I never saw any issues (unless someone else can see any).
So now, I assumed that the issue is on the masterpage. I've went through the masterpage, comparing it with an old website I built and couldn't find the issue.
Head:
<head id="Head1" runat="server">
<title>Page.Title</title>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Pinyon+Script' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Quicksand:400,700' rel='stylesheet' type='text/css'>
<link href="css/bootstrap.css" rel='stylesheet' type='text/css'/>
<link href="css/style.css" rel="stylesheet" type="text/css" media="all"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="js/jquery.min.js"></script>
</head>
Body:
<body>
<div class="header">
<div class="top-header">
<div class="container">
<div class="logo">
<img src="images/logo.png"/>
</div>
<span class="menu"> </span>
<div class="m-clear"></div>
<div class="top-menu">
<ul>
<li class="scroll">HOME</li>
<li><a class="scroll" href="facilities.aspx">FACILITIES</a></li>
<li><a class="scroll" href="pricing.aspx">PRICS</a></li>
<li><a class="scroll" href="contactUs.aspx">CONTACT US</a></li>
</ul>
<script>
$("span.menu").click(function () {
$(".top-menu ul").slideToggle(200);
});
</script>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
<div id="body">
<asp:ContentPlaceHolder runat="server" ID="FeaturedContent" />
<section class="content-wrapper main-content clear-fix">
<asp:ContentPlaceHolder runat="server" ID="MainContent" >
</asp:ContentPlaceHolder>
</section>
</div>
</>
<!---->
<div class="fotter">
<div class="container">
<h3>143 City Located Hotels World Wide</h3>
<h4>"Hospitality, Quality & Good Locations. We only provide you with the best hotels" - John Deo</h4>
<i class="man"></i>
</div>
</div>
<!---->
<div class="fotter-info">
<div class="container">
<div class="col-md-5 details">
<div class="hotel-info">
<h4>ABOUT THIS HOTEL</h4>
<p>This hotel is a 4 Star Hotel found on the Isle of Mull, in Scotland. </p>
<p><b>In order to book for this hotel, you will require to create an account online!</b></p>
</div>
<div class="news">
<h4>LATEST NEWS</h4>
<h5>Grand Hotel Joins DeluxelHotels</h5>
15 AUG
<h5>Happy Chirstmas To Everyone</h5>
15 AUG
<h5>Best Places To Visit 2014</h5>
15 AUG
<h5>Various Offers</h5>
15 AUG
</div>
<div class="clearfix"></div>
</div>
<div class="col-md-7 details">
<div class="join">
<h4>JOIN DELUXEHOTELS</h4>
<p>
TBA
</p>
<p>TBA</p>
READ MORE
</div>
<div class="member">
<h4>MEMBERS AREA</h4>
<form id="Form1" runat="server">
<p>Username</p>
<asp:textbox id="txtUsername" runat="server"></asp:textbox>
<p>Password</p>
<asp:textbox id="txtPassword" textmode="Password" runat="server" />
<asp:button id="logoutBtn" runat="server" text="LOGOUT" visible="false" onclick="logoutBtn_Click" />
<asp:button id="loginBtn" runat="server" text="LOGIN" onclick="loginBtn_Click" />
<asp:button id="registerBtn" runat="server" text="REGISTER" onclick="registerBtn_Click" />
</form>
</div>
<div class="clearfix"></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</body>
Now just to add on as a side-note.
I'm currently using a BootStrap UI Template for my website. I've took highlights of pieces of code which would/could be causing the problem
Things that I have noticed/tried:
- Buttons on MasterPage work fine.
- Buttons on 'registration' page don't work (i.e reset and submit)
- The parameter on the registration page was too big, so placed all details in that method instead
- MasterPage MainContent - Placing a Form within this.
- Removing all forms
- Create a new testpage which doesn't use MasterPage (buttons do work)
- Compared with my other website
I'm no expert at fixing issues, and have struggled to find this error, which you'll most likely find much more quickly than myself.
I'd like to apologise for such a large issue/question, but I'd like to get this sorted and not repeat my problem again in the future.
Thanks for looking at this.
I never found the issue. However, I found a workaround until I can find a sufficient alternative.
I started a new Project in Visual Studio, and decided to pick out every piece of information which would be an absolute necessity for the Website to still look relatively decent, and work.
[This means, I have one form over a contentplaceholder, which is holding everything, including another contentplaceholder where the information from every other page is in that placeholder].
I am still getting a few of the errors (which are easily fixable), however the override class is now, not being used due to some debugging finds, I found that it was overriding the button onClicks.

Error Object reference not set when using UpdatePanel

I had this error " Object reference not set .... " , I had checked my
code and I got that the error in UpdatePanel , when i removed it the
code worked well but I must use it to prevent all page reload .
<div>
<fieldset style="width: 498px; text-align: right; padding: 5px; direction: rtl;">
<legend>what do y think ? </legend>
<div class="add-post">
<textarea class="textarea" cols="3" rows="3" runat="server" id="txpost"></textarea>
<asp:RequiredFieldValidator ID="RVAddPost" runat="server" ForeColor="Red" ErrorMessage="*"
ControlToValidate="txpost" ValidationGroup="AddUserPost">*</asp:RequiredFieldValidator>
</div>
<asp:UpdatePanel ID="UPAddUserPost" runat="server">
<ContentTemplate>
<div class="add-post-control">
<div class="post">
<asp:Button Text="Submit" runat="server" ID="btAddPost" OnClick="btAddPost_Click" ValidationGroup="AddUserPost" />
</div>
<div class="fileUpload btn btn-primary">
<div class="fileUpload btn btn-primary">
<span>
<img src="res/images/img.png" width="38" height="27" /></span>
<input type="file" runat="server" class="upload" id="FUFile" />
</div>
</div>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btAddPost" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</fieldset>
<script type="text/javascript">
$('.textarea').focus(function () {
$(this).animate({
height: "80px"
}, 500);
$('.add-post-control').fadeIn(200);
});
</script>
</div>
Method:
protected void btAddPost_Click(object sender, EventArgs e)
{
AddpostfromFront();
}
private void AddpostfromFront()
{
if (FUFile.PostedFile.ContentLength != 0)
{
string tempVar = "~/res/Posts/" + FUFile.Value.ToString();
FUFile.PostedFile.SaveAs(Server.MapPath(tempVar));
ftier.Addpostfromfront(LoggedUserID, "4", txpost.Value, tempVar, DateTime.Now, DateTime.Now, false, false);
}
}
I think what you need to do instead of check the length of the file is to use a method that is built into PostedFile to check if there is a file to begin with.
if you look on the Microsoft page for PostedFile your code would look more like this
Private void AddpostfromFront() //I don't like your naming on this, should be AddPostFromFront
{
if (FUFile.HasFile)
{
string tempVar = "~/res/Posts/" + FUFile.Value.ToString();
FUFile.SaveAs(tempVar);
}
}
to use these methods you may have to use the ASP control instead of the HTML tag, <asp:FileUpload></asp:FileUpload> you will have to adjust the attributes to fit your situation and naming scheme. This would replace your HTML tag <input type="file" runat="server" class="upload" id="FUFile" />
I think that you are meshing two processes into one and getting confused as to what your code should be doing.
no clue what ftier is and why it has the same method name with the same bad naming scheme, or what it is doing with that information.
you should do this in 3 steps
upload the file
save the file
if you need to display the file then do so with the file that is saved, not the file that is being uploaded.

Updating the master page when the control is within an update panel on the content page

I have an application which has a control within a update panel but needs to update a part of the master page aswel - i m not sure if this can be done?
The
<asp:ScriptManager ID="ScriptManager" runat="server" />
is within the master page
and the part of the master page i want to update is the following:
<div id="divPanelMyCover" class="divPanelMyCover" runat="server">
<div class="sectionYourProtection">
<div class="sectionPadding">
<h4>Title</h4>
</div>
<div class="innerPanelMyCover">
<br/>
<ul class="bulletList" type="square">
<li><span class="spBold">Monthly Payment: </span><asp:Label ID="lblMonthlyPayment" runat="server" Text=""></asp:Label </div>
</div>
</div>
code behind:
lblMonthlyPayment.Text = Convert.ToString(application.Premium);
The lblMonthlyPayment needs to change depending on what the user selects on a content page but as the control is within an update panel it is not working.
Content page:
<asp:UpdatePanel ID="upUpSell" runat="server">
<ContentTemplate>
<div id ="divSlider" runat="server" visible="false">
<br />
<h3>If you want, you can change the amount ... </h3>
<hr />
<div class="sliderContainer">
<telerik:RadSlider id ="rdSlider" AutoPostBack="true" runat="server" Orientation="Horizontal" Width="450"
Height="70" MinimumValue="0" MaximumValue="50" LargeChange="10" TrackPosition="BottomRight"
ItemType="Tick" IsSelectionRangeEnabled="false" SelectionStart="10" SelectionEnd="30" Skin="Default" DragText="Select Premium" >
</telerik:RadSlider>
</div>
<asp:Label ID="lblValue" runat="server" Text="" Visible="false"></asp:Label>
</div>
c#
protected void Page_Load(object sender, EventArgs e)
{
//if (!Page.IsPostBack)
//Pre-populate the screen with data from ApplicationBO
ApplicationBO application = (ApplicationBO)Session["Application"];
if (!Page.IsPostBack)
{
if (Session["Application"] == null)
application = new ApplicationBO();
else
application = (ApplicationBO)Session["Application"];
lblclientName.Text = application.FirstName;
rdSlider.Value = Convert.ToDecimal(application.Premium);
lblMonthlyPayment.Text = Convert.ToString(application.Premium);
}
divSlider.Visible = true;
string upsellValue = Convert.ToString(application.Premium);
if (divSlider.Visible == true)
{
upsellValue = Convert.ToString(rdSlider.Value);
// Save the current page information
application.Premium = Convert.ToDecimal(upsellValue);
}
Thanks in advance...
Wrap the label with an UpdatePanel with UpdateMode="Always"

Categories