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.
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>
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.
I've got an issue with a messagebox user control. I wish for a control which can be given a message and the user can dismiss with a click of a button, which can be inserted into many places.
I have applied the javascript into the messagebox control in a hope i can keep everything to do with the messagebox centralized, however when browsing to a page with the messagebox control added i get this error:
CS1061: 'ASP.components_messagebox_ascx' does not contain a definition for 'HideBox' and no extension method 'HideBox' accepting a first argument of type 'ASP.components_messagebox_ascx' could be found
The control is as thus:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Messagebox.ascx.cs" Inherits="FosterNetwork.Components.Messagebox" %>
<script type="text/Javascript">
function HideBox() {
document.getElementById("PNL_Messagebox").setAttribute("visible", false);
}
</script>
<asp:Panel ID="PNL_Messagebox" runat="server">
<asp:Label ID="LBL_Message" runat="server" />
<asp:Button ID="BTN_Ok" Text="Ok" OnClick="HideBox()" runat="server" /> <!--Error happens on this line-->
</asp:Panel>
I'm fairly certain i've done this right but obviously i've done something wrong if it's not working. Any light on the situation at all would be grand.
Addendum: If i comment out the Button control the page loads fine, and the script loads fine too (Viewed page source)
The control ID's you're referencing are not the client ID's, but server ID's. So retrieve the 'ClientID' from the control in the JavaScript function and second, use the 'OnClientClick' property to show the JavaScript message.
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Messagebox.ascx.cs" Inherits="FosterNetwork.Components.Messagebox" %>
<script type="text/Javascript">
function HideBox() {
document.getElementById("<%= PNL_Messagebox.ClientID %>").setAttribute("visible", false);
}
</script>
<asp:Panel ID="PNL_Messagebox" runat="server">
<asp:Label ID="LBL_Message" runat="server" />
<asp:Button ID="BTN_Ok" Text="Ok" OnClientClick="HideBox()" runat="server" /> <!--Error happens on this line-->
</asp:Panel>
Onclick looks for a server side function, and not javascript. either, define your button as <input type='button' onclick='HideBox' or change the current code to:
<script type="text/Javascript">
function HideBox() {
document.getElementById("<%= PNL_Messagebox.ClientID %>").setAttribute("visible", false);
return false;
}
</script>
<asp:Button ID="BTN_Ok" Text="Ok" OnClientClick="return HideBox()" runat="server" />
returning false in OnClientClick, prevents the asp button from postback.
Edit: as Monty mentioned, your panel control's client id is not correctly set in your code.
I am using ASP.NET 2.0 and VB.NET (C# code will also help me out)
On top of my page I have a button called btnViewRecords. When the User click on the button I want to set focus to another button or label further down on the same page. How can this be done.
This code does not work for me..............
btnTheRecords.Focus()
or
lblHeader.Focus()
Thanks in advance!!
Edit:
Even if my code did work, i dont want to reload the page every time.
Here's a relatively simple solution...
<asp:Button ID="Button1" runat="server" Text="Button"
OnClientClick="return SetFocus()" />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<script type="text/javascript">
function SetFocus() {
document.getElementById('<%=TextBox2.ClientID %>').focus();
//or this if you're using jQuery
//$("#<%=TextBox2.ClientID %>").focus();
return false;
}
</script>
You can use JavaScript to do this.
document.getElementById ( "btnTheRecords" ).focus();
By setting focus what do you mean. Do you want to bring this control into view if it is way down the page. Then there are better ways to do this.
Edit:
You can place an anchor tag near the button or the bale and set
location.href = "#anchorId";
where anchorId is the id of the anchor tag.
will move the focus to the anchor tag.
Try this,
I wrote a small code and it seems to be working for me. sorry this is in C# but if you click on a button and set focus on another button then page will automatically scroll down for you.
ASP.NET
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
<div style="height:50px;"></div>
<div>
<asp:Button ID="Button1" runat="server" Text="Button 1" onclick="Button1_Click" />
</div>
<div style="height:1000px;"></div>
<div>
<asp:Button ID="Button2" runat="server" Text="Button 2" onclick="Button2_Click" />
</div>
</form>
</body>
</html>
AND Code Behind
using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Button2.Focus();
Label1.Text = "button1 clicked & button2 in focus";
}
protected void Button2_Click(object sender, EventArgs e)
{
Button1.Focus();
Label1.Text = "button2 clicked & button1 in Focus";
}
}
I'm not sure exactly of the problem you're having. But in cases where the SetFocus() function and such just don't work (and they often don't in VB for some reason). I've often used workarounds such as shortcut Keys & mnemonics in combination with SendKeys() to get focus where I need it to be.
Depending on whether the buttons you are talking about are in your ASP.NET code or in your VB.NET code, this may be a viable workaround for you as well.
document.getElementById("spanId").scrollIntoView(false)
Reference:
.scrollIntoView
If the button is server side, set the "OnClientClick"
action on it to a javascript function. Cancel windows
events so the page location does not change.
function goto(){
window.event.cancelBubble = true;
window.event.returnValue = false;
document.getElementById("pageloction").focus()
}
asp:Button runat="server" ID="btnTheRecords" OnClientClick="javascript:goto()" />
span id="pageloction">