I have an ASPX view in my MVC application that has a FileSelector, a label, and a button that is supposed to put the FileSelector's selected file name and size into the label (this is for testing purposes; the final version will send the FileSelector's FileBytes byte array to an SQL Server database). Hoewver, when I press the button, the page refreshes, and the label is unchanged.
Here is the view code:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html>
<html>
<script runat="server" language="C#">
void btnLoad_Click(Object sender, EventArgs e)
{
byte[] B = FileSelector.FileBytes;
lblStatus.Text = "File \"" + FileSelector.FileName + "\" has size " + B.Length;
}
</script>
<head runat="server">
<title>ABMC - Add Photo (ASPX version) </title>
</head>
<body>
<div>
<form runat="server">
<asp:FileUpload ID="FileSelector" runat="server" />
<br /><br />
<asp:Button ID="btnLoad" Text="Load" runat="server" OnClick="btnLoad_Click" />
<br /><br />
<asp:Label ID="lblStatus" runat="server">No file selected yet</asp:Label>
</form>
</div>
</body>
</html>
When I select a file and then click on the "Load" button, the page refreshes, and the label still reads, "No file selected yet."
I did manage to get this to work (sort of) by using a separate ASPX form (with the code in a separate .aspx.cs file) rather than an MVC View, but I have to pass a Model back to the page that called this page, so I would prefer doing this in a View.
Maybe you need to add "return false" to the btnLoad_Click call. Try using return btnLoad_Click and returning false from that function.
Related
I have created a ASP.NET Empty Website in a new install of Visual Studio 2017 Community. I am attempting to replicate the steps shown by the following tutorial: https://youtu.be/5dCAXwhjIYU
I'm simply planting three text boxes on the form, along with a submit button. When i double click the button, The IDE simply highlights the HTML for the button in the source view of the page. It does not create the event handler in the code-behind as shown in the video and as expected.
I manually created the event handler for the button click in the code behind. When I try to run the code, it is telling me that the fields I'm referencing do not exist:
Error CS0103 The name 'UserName' does not exist in the current context
Here's my HTML code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Users.aspx.cs" Inherits="Users" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
UserName<br />
<input id="UserName" type="text" /><br />
UserEmail<br />
<input id="UserEmail" type="text" /><br />
UserCampus<br />
<input id="UserCampus" type="text" /><br />
<input id="SaveUser" type="submit" value="submit" /></div>
</form>
</body>
</html>
The C# code:
public partial class Users : System.Web.UI.Page
{
protected void SaveUser_Click(object sender, EventArgs e)
{
SqlConnection BIGateConnection = new SqlConnection("Data Source=xxxxxxx;Initial Catalog=xxxxxxx;Integrated Security=True");
{
SqlCommand BIGateSQLCmd = new SqlCommand("Insert into [BIGateway].[dbo].[User] (UserName, userEmail, userCampus) VALUES (#userName, #userEmail, #userCampus)", BIGateConnection);
BIGateSQLCmd.Parameters.AddWithValue("#", UserName.Text);
BIGateSQLCmd.Parameters.AddWithValue("#", UserEmail.Text);
BIGateSQLCmd.Parameters.AddWithValue("#", UserCampus.Text);
}
}
}
What the heck am I doing wrong?
if you have taken HTML text box then code is as follows:
<input id="UserName" type="text" /><br />
In this you will have to add the line on your own as runat="server"
It will look as follows:
<input id="UserName" type="text" runat="server"/><br />
Then you can use it for serverside.
Hope its helpful.
Video doesn't show the ASPX page. I believe he used TextBox and Button server controls.
<form id="form1" runat="server">
<div>
UserName<br />
<asp:TextBox runat="server" ID="UserName"/><br />
UserEmail<br />
<asp:TextBox runat="server" ID="UserEmail"/><br />
UserCampus<br />
<asp:TextBox runat="server" ID="UserCampus"/><br />
<asp:Button runat="server" ID="SaveUser" OnClick="SaveUser_Click" Text="Submit"/>
</div>
</form>
If he used regular html input with runat="server", he will have to access the value as UserName.Value inside Button1_Click event which he did not.
Afais you didn't find the click event to the button.
Add
SaveUser.OnClick += SaveUser_Click;
To the page_load event.
In general I would prefer asp:Button instead of input.
In fact it's rendered as a input control. But with more options. But indeed runat="server" is missing for the input.
I have an update panel on a page which contains nested Panels. It has a Panel with a small form (like a log-in form) and a button. When the button is clicked, a few conditions are checked, and if passed, the first Panel is hidden and the second Panel with a larger form is displayed.
Because the larger form can take some time to load (it pulls data from other sources), the small form panel contains an UpdateProgress control.
All of this works fine.
Then I added a nested Panel within the login form Panel, placed under the UpdateProgress that will display a meaningful error message, such as if the login code is incorrect. This displays as expected. However, if the user then corrects their information and clicks the button again, the UpdateProgress displays properly, but the error message remains visible, even though I try to set it to Visible = false in code-behind.
This page does not use a master page.
Debugging shows that the Visible property does get set to false, although it still displays in the browser.
ASPX code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="custom_Default" %>
<!DOCTYPE html>
<html lang="en">
<head runat="server">
<!-- meta and link tags -->
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<!-- h1 and all that -->
<asp:ScriptManager ID="scriptManager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="pnlUpdate" runat="server">
<ContentTemplate>
<asp:Panel ID="pnlLogin" runat="server">
<!-- label and text field -->
<asp:Button ID="btnBegin" runat="server" OnClick="btnBegin_Click" />
<asp:UpdateProgress ID="updProgress" runat="server" AssociatedUpdatePanelID="pnlUpdate">
<ProgressTemplate>
<p>Loading, please wait... </p>
</ProgressTemplate>
</asp:UpdateProgress>
<asp:Panel ID="pnlMessage" runat="server" Visible="false">
<asp:Literal ID="ltlMessage" runat="server" />
</asp:Panel>
</asp:Panel>
<asp:Panel ID="pnlMainForm" runat="server" Visible="false">
</asp:Panel>
<asp:Panel ID="pnlConfirmation" runat="server" Visible="false">
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
<!-- javascript - jquery and bootstrap -->
</body>
</html>
Code Behind (I've tried setting visible to false in the Page_Load, in the pnlUpdate_Load event, and in the btnBegin_Click event - but that error message will not go away.
protected void btnBegin_Click(object sender, EventArgs e)
{
pnlMessage.Visible = false;
Page.Validate();
if (Page.IsValid)
{
// check some conditions. if fails:
ltlMessage.Text = "Reason for failure";
pnlMessage.Visible = true; // works
}
}
I have tried removing the Visible="false" from the pnlMessage on the ASPX page and placing it in the code behind in Page_Load but I still can't hide it after the message has already been displayed.
How can I hide the pnlMessage Panel after the btnBegin is clicked the second time?
I managed to find the solution to this. Apparently there isn't a way to do it in .NET - it has to be done in JavaScript.
Here is the code I used to accomplish this.
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(initializeRequest);
prm.add_endRequest(endRequest);
var _postBackElement;
function initializeRequest(sender, e) {
if (prm.get_isInAsyncPostBack()) {
e.set_cancel(true);
}
$get('pnlMessage').style.display = 'none';
}
function endRequest(sender, e) {
$get('pnlMessage').style.display = 'block';
}
</script>
In my asp.net page I have Image control , in which myimage.png will display at page load. Requirement as below,
Browse image using File upload control and on click of Upload button , immediate preview need to be displayed in Image control. When upload button is pressed after browsing image, the existing "myimage.png" will be deleted and new image will be saved into sever path with same name and preview need to be displayed in image control.
Issue is After saving image , image control is not displaying the new image immediately.
To view the image page need to be re-loaded. Code as below,
In aspx page,
<asp:Image ID="imgLogo" style="margin-left: -299px;" ImageUrl="~/images/myimage.png" runat="server" />
Code behind as below,
protected void btnUpload_Click(object sender, EventArgs e)
{
string filePath = FileUpload1.PostedFile.FileName;
File.Delete(Server.MapPath(#"~\images\myimage.png"));
FileUpload1.SaveAs(Server.MapPath(#"~\images\myimage.png"));
imgLogo.ImageUrl = Server.MapPath(#"~\images\myimage.png");
}
Regards
The reason your page must be reloaded is because ASP.NET code is executed on a server. So every time you, for example, click the button with a server-side code inside, the request is sent to the server, server executes your code and returns a proper response. Basically: something MUST be reloaded. It doesn't have to be the entire page, though. You can force the browser to reload only a certain piece of page using AJAX extensions such as Script Manager and Update Panel.
Example (aspx page):
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Click the button."></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Hello World" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
OnClick event:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Hello world!";
}
Also, you can force the panel to update it's content using the Update() method of the UpdatePanel.
This looks like a browser caching issue.
The url is exactly the same as it was prior to changing the image file, so the cache will use the originally named file (in its cache) to display.
You can get over this hurdle by adding something extra (but not used) to the url:
protected void btnUpload_Click(object sender, EventArgs e)
{
// Do your upload stuff here...
imgLogo.ImageUrl = "~/images/myimage.png?" + DateTime.Now;
}
I am new to web programming. I have a pretty standard page that accepts contact information and I am trying to add validation controls to it. When the user clicks the cancel button nothing is saved so I just want to unload the page and go back to the previous page. My problem is, even the the cancel button has CausesValidation="false the validation events are still firing and a post back does not occur. I am using Visual Studio 2012 and C#. I've created a test page to reduce the code I'm working with to the minimum required code to demonstrate the issue. I have tried the javascript disableValidation() function with both Page_Validation = false; and the loop to disable the individual validation controls without success. When I check Page_Validation it is false, and the loop throws the exception Page_Validators is undefined.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="TestMe.aspx.cs" Inherits="ElmoWeb.TestMe" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Simple Little Test Form</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="uxEmail" runat="server" placeHolder="email address" type="email" AutoCompleteType="Email"></asp:TextBox>
<asp:RegularExpressionValidator ID="uxEmailValidator" runat="server"
ControlToValidate="uxEmail"
ValidationExpression="^[a-zA-Z][\w\._%+-]*[a-zA-Z0-9]#[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"
ErrorMessage="The email address is invalid"
EnableClientScript="false" ValidationGroup="testing"
Display="Static"/>
</div>
<div>
<asp:Button ID="Submit" runat="server" Text="Submit" CausesValidation="true" UseSubmitBehavior="true" ValidationGroup="testing" />
<asp:Button ID="Cancel" runat="server" Text="Cancel" CausesValidation="false" UseSubmitBehavior="true" ValidationGroup="FakeValidationGroup" />
</div>
<div>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" DisplayMode="List" HeaderText="You must correct the following errors." ValidationGroup="testing" />
</div>
</form>
</body>
</html>
Currently the code behind just writes a message to the output window so I can see if the post back occurred.
protected void Page_Load(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("TextMe.aspx Page_Load event, sender = " + sender.ToString() + ", EventArgs = " + e.ToString());
}
The natural way of solving issues where two or more submit buttons should behave in a different way is to use validation groups.
A validation group is set with the ValidationGroup attribute on both a submit button and a group of validators. The same value binds a button and validators and only validators with the same value of the attribute fire when the button is clicked.
In your case, setting the ValidationGroup on the accept button and your validators to "Accept" and leaving the default (empty) value on the cancel button would solve your issue. This is much simpler than any of the workarounds you tried.
Hi all I have an update panel that works lovely in my test solution but when I put it into the main project it does not work correctly.
I've made it very simple, but still no joy, it consists of:
the file upload control
a link button
the link button has an onclick method that takes the file and creates a byte array. For some reason the contentLength is -2 every time. It does not matter what type of file I am using. Every time!
This is very frustrating considering it works fine in my test solution.
Is there anything I am missing or should be looking at?
Thanks :)
EDIT:
I am using VS2008
CODE:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:LinkButton ID="btnUpload" runat="server" ValidationGroup="uploadform" CssClass="uploadbutton" OnClick="btnUpload_Click">Upload</asp:LinkButton>
</form>
</body>
</html>
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
var intDoccumentLength = FileUpload1.PostedFile.ContentLength;
// will crash here as content length is -2 for some reason~???
byte[] newDocument = new byte[intDoccumentLength];
}
Your test code must be doing complete postback which is not the case for Updatepanel part as part of main project. With updatepanel, file may not have been uploaded at point of time when you are checking its contentlenght; this is not true for complete postback where file always gets uploaded first. In this case, it will always through you an error. This can only be done using an ActiveX control of some kind.
This article may give you nice hint and direction: asp.net FileUpload event after choice is made and before submit for upload
The file up loader is not working well in the update panel so if you are using the update panel then you have to use the triggers in the update panel and you have to give the name of the control or button on which you are clicking to upload the file
<%# Page Language="C#" MasterPageFile="~/FullViewMasterPage.master" AutoEventWireup="true" CodeFile="Test1.aspx.cs" Inherits="Test1" Title="Untitled Page" %>
<%# Register TagPrefix="yaf" Namespace="YAF" Assembly="YAF" %>
<%# Register TagPrefix="yc" Namespace="YAF.Controls" Assembly="YAF" %>
<asp:Content ID="Content1" ContentPlaceHolderID="FullViewContentPlaceHolder" Runat="Server">
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:FileUpload id="fileUpload" runat="server" ></asp:FileUpload>
<asp:Button ID="Upload" runat="server" OnClick="Upload_Click" Text="Upload The Image" /><br />
</ContentTemplate>
</asp:UpdatePanel>
<br />
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Upload" EventName="Upload_Click" />
</Triggers>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:Label ID="lblTime3" runat="server" /><br />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</asp:Content>
<code>
As FileUpload.PostedFile.InputStream.Length returns the same as FileUpload.PostedFile.ContentLength, did you check that your file size is lower than maxRequestLength (4MB by default) or specified in web.config :
<system.web>
<httpRuntime maxRequestLength="8192"/>
</system.web>
See : http://msdn.microsoft.com/en-us/library/system.web.configuration.httpruntimesection.maxrequestlength.aspx