Error Object reference not set when using UpdatePanel - c#

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.

Related

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

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.

Trying to apply bootstrap styles in ASP.net webform

I have a text box which has an asp:RegularExpressionValidator attached to it as so
<div class="form-group col-sm-6 <%= (revAlertValue.IsValid == false ? "has-error" : "") %>">
<label for="AlertValue" class="control-label col-sm-4">Alert Value</label>
<div class="col-sm-4 input-group">
<span class="input-group-btn">
<asp:Button ID="btnMediumValue" CssClass="btn btn-warning" runat="server" Text="Low" OnClientClick="btnMediumValue_Click" OnClick="btnMediumValue_Click" />
</span>
<asp:TextBox CssClass="form-control text-center" CausesValidation="true" ID="tbAlertValue" runat="server" MaxLength="4" />
<asp:RegularExpressionValidator ID="revAlertValue" runat="server"
ControlToValidate="tbAlertValue" ErrorMessage=""
ValidationExpression="^[1-9]\d*$" />
<asp:RequiredFieldValidator ID="rfvAlertValue" runat="server" ControlToValidate="tbAlertValue" />
<span class="input-group-btn">
<asp:Button ID="btnHighValue" CssClass="btn btn-danger" runat="server" Text="High" OnClientClick="btnHighValue_Click" OnClick="btnHighValue_Click" />
</span>
</div>
I'm basically trying to apply the has-error class to my form-group if the regular expression validator is not valid. However, when I go to test and input text that would fail the regex validator the class is not applied.
I've tried writing the expression in other ways:
<%= (revResendEvery.IsValid == false) ? "has-error" : "" %>
<%= (revAlertValue.IsValid == false ? "has-error" : "") %>
I've thought maybe it has to be triggered when the submit button is pressed, or more code has to be added to the .aspx.cs handling the class addition after submit is pressed but that doesn't do the trick either.
In order to do this client side you need to tap into the client side code rendered by ASP.NET. Here is an example of some script you might include on your page to do so.
(function () {
var originalRegularExpressionValidator = RegularExpressionValidatorEvaluateIsValid;
RegularExpressionValidatorEvaluateIsValid = function (val) {
var originalValidationResult = originalRegularExpressionValidator(val);
if (!originalValidationResult) {
var formGroup = $("#" + val.controltovalidate).closest(".form-group");
formGroup.addClass("has-error");
}
return originalValidationResult;
}
})();
This, of course, assumes you have jQuery on the page (for the closest and addClass methods), but you can replace that with whatever you want.
Additionally, you may want to look into overriding the Page_ClientValidate function ASP.NET renders. There are many questions on StackOverflow that address how to do that.

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.

How can I prevent C# from redrawing a <div> I used jQuery to show

Scenario: I have a modal-style div that will be shown when the user clicks a button. At the time the div is shown, I need to get some data from the back-end to fill in some fields. Additionally, I'd like to use the jQuery method I use for all my modal windows (fades in the modal div, displays a background div as well as enabling the use of ESC key or "click offs" to close the modal).
It looks something like this:
<asp:ScriptManager ID="sc" runat="server" />
<asp:UpdatePanel ID="updForm" runat="server">
<ContentTemplate>
<h4>Testing jQuery calls combined with code behind actions</h4>
<div class="pad-content">
<asp:LinkButton ID="lnkShowIt" runat="server" OnClick="lnkShowIt_Click" Text="Load Form" OnClientClick="showForm()" />
<asp:Panel ID="pnlPopup" ClientIDMode="Static" runat="server" CssClass="box-modal" style="width:500px;display:none;z-index:1001">
<div class="header">Edit Estimate X</div>
<div class="content">
<div class="window">
<h5>Test Form</h5>
<asp:TextBox ID="tbxTime" runat="server" />
<br />
<asp:TextBox ID="tbxText" runat="server" Width="150px" />
<br />
<asp:LinkButton ID="lnkValidate" runat="server" CssClass="link-button-blue" Text="Validate" OnClick="lnkValidate_Click" />
</div>
</div>
</asp:Panel>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<div id="backgroundPopup"></div>
So ... lnkShowIt calls both the jQuery (which will show pnlPopup) as well as the C# (which will populate tbxTime).
jQuery method actually just calls another method from a common js library I have that does the modal window stuff - I don't think that actual code is the problem but here is the simple function used for this page:
<script type="text/javascript" language="javascript">
function showForm() {
loadPopup('#pnlPopup');
}
</script>
Code behind methods look like this:
protected void lnkShowIt_Click(object sender, EventArgs e)
{
tbxTime.Text = System.DateTime.Now.Second.ToString();
}
protected void lnkValidate_Click(object sender, EventArgs e)
{
if (tbxTime.Text == tbxText.Text)
{
Response.Redirect("DynamicBoxesWithJQuery.aspx?mode=success");
}
else
{
tbxText.Style["border"] = "1px solid red";
}
}
I'm able to generate some level of success by doing the following but it seems like just a major hack and I have to assume there's a better approach:
protected void lnkShowIt_Click(object sender, EventArgs e)
{
tbxTime.Text = System.DateTime.Now.Second.ToString();
ScriptManager.RegisterStartupScript(this, this.GetType(), "OpenEditor", "<script type='text/javascript'>loadPopup('#pnlPopup');</script>", false);
}
protected void lnkValidate_Click(object sender, EventArgs e)
{
if (tbxTime.Text == tbxText.Text)
{
Response.Redirect("DynamicBoxesWithJQuery.aspx?mode=success");
}
else
{
tbxText.Style["border"] = "1px solid red";
ScriptManager.RegisterStartupScript(this, this.GetType(), "OpenEditor", "<script type='text/javascript'>loadPopup('#pnlPopup');</script>", false);
}
}
It seems like it should be easier than this, but the way the UpdatePanel keeps redrawing (and thus resetting the display:none on pnlPopup) is really causing me fits.
Thanks in advance
Solution I just found: putting the LinkButton in its own UpdatePanel and then the form in its own UpdatePanel and making sure the div that is the actual popup box is not in an UpdatePanel at all.
<h4>Testing jQuery calls combined with code behind actions</h4>
<div class="pad-content">
<asp:UpdatePanel ID="updLink" runat="server">
<ContentTemplate>
<asp:LinkButton ID="lnkShowIt" runat="server" OnClick="lnkShowIt_Click" Text="Load Form" OnClientClick="showForm()" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Panel ID="pnlPopup" ClientIDMode="Static" runat="server" CssClass="box-modal" style="width:500px;display:none;z-index:1001">
<div class="header">Edit Estimate X</div>
<div class="content">
<asp:UpdatePanel ID="updForm" runat="server">
<ContentTemplate>
<div class="window"style="min-width:500px;">
<h5>Here is a Test Form</h5>
<label>Time:</label>
<asp:TextBox ID="tbxTime" runat="server" />
<br />
<asp:Label ID="lblText" AssociatedControlID="tbxText" runat="server" ViewStateMode="Disabled">Text:</asp:Label>
<asp:TextBox ID="tbxText" runat="server" Width="150px" />
<br />
<asp:LinkButton ID="lnkValidate" runat="server" CssClass="link-button-blue" Text="Validate" OnClick="lnkValidate_Click" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</asp:Panel>
</div>
Seems to do the trick without any Script Registers from the codebehind

fileupload's upload button works different in IE and Chrome

For those who worked with bootstrap, knows it does not support input type = file, so I hide the asp:fileupload using jQuery (after document ready), and have and for the solution (as you can see from the code
<script type="text/javascript">
$(document).ready(function ()
{
$('#columnSelect').change(function ()
{
getImportColumnOrder();
});
// change file upload style similiar to bootstrap style
//$('#uploader').hide();
$('#uploader').change(function ()
{
var val = $(this).val();
var file = val.split(/[\\/]/);
$('#file').val(file[file.length - 1]);
});
});
function getImportColumnOrder()
{
var order = '';
$('#selectOrer').val('');
$('select', $('#MappingTable')).each(function ()
{
order += $(this).prop('selectedIndex') + ',';
});
$('#selectOrder').val(order.substr(0, order.length - 1));
}
</script>
<div class="span12">
<asp:DropDownList ID="ddl_DBTableList" runat="server" CssClass="combobox" Style="display: inline">
<asp:ListItem></asp:ListItem>
<asp:ListItem Value="Import_Test">Import_Test</asp:ListItem>
</asp:DropDownList>
<asp:FileUpload ID="uploader" runat="server" CssClass="btn" />
<div class="input-append" style="display: inline;">
<input id="file" class="input-medium" type="text" />
<a class="btn" onclick="$('input[id=uploader]').click();">Select File</a>
</div>
<p />
<div>
<asp:Button ID="btn_uplaod" runat="server" OnClick="doUpload" Text="Upload" CssClass="btn" />
</div>
<p />
<asp:Label ID="result" runat="server" ForeColor="Red"></asp:Label>
<p />
<asp:Label ID="data" runat="server" BackColor="#CCCCCC"></asp:Label>
<p />
<asp:Button ID="btn_import" runat="server" Text="Next" OnClick="doImport" OnClientClick="getImportColumnOrder();return true;" Visible="false" CssClass="btn btn-success" />
</div>
Steps are click on the "Select File", a file chooser popped up for file selection. After double clicked a file, the file location gets displayed in , and also the asp fileupload control.
In Chrome and FF, when I clicked btn_uplaod (button), it runs as supposed. In IE, it will clear the fileupload's content and does nothing (a client side action) and will not do any postback.
If this is a program problem, then maybe Chrome and FF will not run correctly. I'm suspecting is there anything that I need to add to make IE run as suppose to?
image after click upload (IE), (Browse link is cleared)
image after click upload (Chrome), (Run as supposed to)
thanks!
I've made a simple version for those of you who wants to try on Visual studio:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="postback_problem.aspx.cs" Inherits="postback_problem" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> </head> <body> <form id="form1" runat="server"> <div> <asp:FileUpload ID="uploader" runat="server" CssClass="btn" /> <div> <input id="file" class="input-medium" type="text" /> <a onclick="$('input[id=uploader]').click();">Select File</a> </div> <p /> <div> <asp:Button ID="btn_uplaod" runat="server" OnClick="doUpload" Text="Upload" CssClass="btn" /> </div> <asp:Label ID="result" runat="server"></asp:Label> </div> </form> </body> </html>
and
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class postback_problem : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void doUpload(object sender, EventArgs e) { result.Text = "no problem!"; } }

Categories