Fileupload hasfile returns false on first postback - c#

I have a file upload located in div element. The form element is located in master file. HasFile property always returns false on first postback.
Asp.net Code
<div class="form-horizontal center-block" role="form" id="uploadFilesForm">
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="fileUpload" CssClass="col-md-4 control-label">Select Files</asp:Label>
<div class="col-md-8">
<asp:FileUpload runat="server" ID="fileUpload" AllowMultiple="True" />
</div>
</div>
<div class="form-group">
<asp:Label runat="server" CssClass="col-md-4 control-label"></asp:Label>
<div class="col-md-8">
<asp:Button runat="server" id="uploadButton" text="Upload" CssClass="btn btn-primary" OnClick="uploadButton_Click"/>
</div>
</div>
</div>
C# Code:
protected void Page_Load(object sender, EventArgs e)
{
Page.Form.Enctype = "multipart/form-data";
}
protected void uploadButton_Click(object sender, EventArgs e)
{
if (fileUpload.HasFile) // this returns false on first postback
{
//more code
}
}

Add the following code in your OnInit() method:
Page.Form.Attributes.Add("enctype", "multipart/form-data");

Related

How to use the asp.net button to validate by jquery and then go to the behind code web form

I have an asp.net webform and I want to validate the textboxes first
Then after that (after success), go to the behind code cs
but now when I press the button it doesn't work
the jquery code:
...
<script type="text/javascript">
(function () {
'use strict';
window.addEventListener('load', function () {
var form = document.getElementById('needs-validation');
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
</script>
...
the aspx page:
...
<div class="form-row" style="z-index:1">
<div class="form-group col-md-4" style="z-index:1">
<label for="inputEmail4">Birth Date</label>
<asp:TextBox ID="Birth_Date" class="form-control" runat="server" style="text-align:center" ValidationGroup="check" required></asp:TextBox>
<cc1:CalendarExtender ID="CalendarExtender1" runat="server" Enabled="True" TargetControlID="Birth_Date" Format="dd/MM/yyyy">
</cc1:CalendarExtender>
<div class="invalid-feedback">
enter date
</div>
</div></div>
<div class="form-row">
<div class="form-group col-md-4">
<label for="inputEmail4">phone number</label>
<asp:TextBox ID="Phone" class="form-control" runat="server" style="text-align:center; z-index:-1" ValidationGroup="check" pattern="^\d{10}$" required></asp:TextBox>
<div class="invalid-feedback">
enter phone
</div>
</div>
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:LinkButton ID="signup" runat="server" CssClass="btn btn-outline-success my-2 my-sm-0">save</asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>
...
the cs code:
...
protected void signup_Click1(object sender, EventArgs e)
{
if(Page.IsValid)
{
Birth_Date.Text = "ُWelcome";
}
}
...
I have more textbox in my aspx page
<script type="text/javascript">
function ftn(){
'use strict';
window.addEventListener('load', function () {
var form = document.getElementById('needs-validation');
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
}
</script>
and add onclientclick property to asp:button
<asp:LinkButton ID="signup" onclientclick="ftn()" runat="server" CssClass="btn btn-outline-success my-2 my-sm-0">save</asp:LinkButton>

Using Request.Params when trying to find Control that caused postback returns the wrong control

I have a button that makes a call to an external url to log in to an accounting program (Xero) using OAuth 2. After receiving the token, etc., the button is hidden and a "Disconnect" button is shown. When the disconnect button is clicked, it is then hidden and the Connect button is displayed again. The problem is if I click the "Connect" button again, on postback it executes the code for the "Disconnect" button again, so I can never repeat the first cycle. The "Connect" button stays and all of the disconnect code runs again. I have tried to capture the postback being called by the first button, so that I could tell the disconnect code not to run again, but it is always null. Even worse, the postback always shows that the "Disconnect" button caused the postback even though it is no longer visible on the page. I do not understand why it is doing this. Both buttons are inside an "Update Panel" so that I can hide/show them.
Here is the button code:
<asp:UpdatePanel runat="server">
<ContentTemplate>
<div class="row" id="XeroNotConnected2" runat="server" visible="false">
<div class="col-sm-12 col-md-6">
<div class="form-group">
<label for="imgXero" class="col-sm-3 control-label"></label>
<div class="col-sm-9">
<asp:ImageButton runat="server" ID="imgXero" ImageUrl="~/assets/img/icons/connect-white.svg" OnClick="btnXeroConnect_Click" UseSubmitBehavior="False" />
</div>
</div>
</div>
</div>
<div id="XeroConnected" runat="server" visible="false">
<div class="row" >
<div class="col-sm-12 col-md-6">
<div class="form-group">
<label for="ddlTenants" class="col-sm-3 control-label">Select an Organization:</label>
<div class="col-sm-9">
<asp:DropDownList runat="server" ID="ddlTenants" CssClass="form-control" AutoPostBack="true" OnSelectedIndexChanged="ddlTenants_SelectedIndexChanged"></asp:DropDownList>
</div>
</div>
</div>
</div>
</div>
<div id="XeroConnected2" runat="server" visible="false">
<div class="row">
<div class="col-sm-12 col-md-6">
<div class="form-group">
<label for="btnDisconnect" class="col-sm-3 control-label"></label>
<div class="col-sm-9">
<button type="button" runat="server" class="btn btn-alt3" id="btnDisconnect" onclick="javascript:OpenModal('disconnectConfirm')"><i class="icon s7-plug"></i> Disconnect Xero</button>
</div>
</div>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
In Page_Load I have:
if(IsPostBack)
{
Control pbControl = GetControlThatCausedPostBack(this.Page);
if (pbControl != null)
{
if (pbControl.ID == "lnkDelete")
{
InitiateConnect = false;
}
}
}
Method used to get Control that caused postback is:
private Control GetControlThatCausedPostBack(Page page)
{
LoggerBA.Log(DB_Context, Path.GetFileName(Request.ServerVariables["SCRIPT_NAME"]), MethodBase.GetCurrentMethod().Name, UtilityBA.LoggerLevel.Debug, "method");
//initialize a control and set it to null
Control ctrl = null;
//get the event target name and find the control
string ctrlName = page.Request.Params.Get("__EVENTTARGET");
if (!String.IsNullOrEmpty(ctrlName))
ctrl = page.FindControl(ctrlName);
//return the control to the calling method
return ctrl;
}
Code in disconnect button is:
protected void lnkDelete_Click(object sender, EventArgs e)
{
if(InitiateConnect == false)
{
InitiateConnect = true;
PageAsyncTask t = new PageAsyncTask(DisconnectTenant);
Page.RegisterAsyncTask(t);
Page.ExecuteRegisteredAsyncTasks();
Session.Remove("OAuthToken");
Session.Remove("xeroToken");
Session.Remove("Tenants");
Session.Remove("xeroTenant");
XeroConnected.Visible = false;
XeroConnected2.Visible = false;
btnDisconnect.Disabled = true;
XeroNotConnected2.Visible = true;
XeroNotConnected1.Visible = true;
}
}
Any assistance is greatly appreciated.

Prevent multiple clicks on bootstrap modal button with ASP.NET

I use boostrap modals for saving data on an ASP.NET Web page and I'm having an issue when users by mistake clicks more than once the "Save" button on the modal. The event fires the number of times the user presses the click. This happens because the modal doesn't closes immediatly. It takes about 1 second to close, enough for the user to click more than once the button.
My database is validated (I'm using Entity Framework) so, there's no duplicate values inserted. But if the user clicks two times, it tries to insert the record two times, and the error message is displayed.
How can I prevent this?
This is the modal code:
<asp:Panel runat="server" ID="pnlBank" DefaultButton="btnSaveBank">
<div class="modal fade" id="modBank" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h4 class="modal-title">Banco</h4>
</div>
<div class="modal-body">
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<div class="form-group">
<div class="row">
<label class="col-md-2 control-label">Name</label>
<div class="col-md-10">
<asp:TextBox ID="txtBankName" CssClass="form-control" runat="server" MaxLength="150"></asp:TextBox>
</div>
</div>
<label class="col-md-2 control-label">Address</label>
<div class="col-md-10">
<asp:TextBox ID="txtBankAddress" CssClass="form-control" runat="server" MaxLength="150"></asp:TextBox>
</div>
</div>
<div class="row">
<label class="col-md-2 control-label">Phone</label>
<div class="col-md-10">
<asp:TextBox ID="txtBankPhone" CssClass="form-control" runat="server" MaxLength="15"></asp:TextBox>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div class="modal-footer">
Cerrar
<asp:Button ID="btnSaveBank" runat="server" Text="Save" CssClass="btn btn-primary" OnClick="btnSaveBank_Click" />
</div>
</div>
</div>
</div>
</asp:Panel>
And this is the code behind:
protected void btnSaveBank_Click(object sender, EventArgs e)
{
Bank newBank = new Bank();
newBank.Name = txtBankName.Text;
newBank.Address = txtBankAddress.Text;
newBank.Phone = txtBankPhone.Text;
using (bankEntity)
{
try
{
bankEntity.Bank.Add(newBank);
bankEntity.SaveChanges();
lblResult.Text = "Bank successfully saved";
ObtenerBancos();
}
catch (Exception ex)
{
lblResult.Text = "Error when saving bank: " + ex.Message;
}
}
}
You can try disabling the save button and closing the modal via jQuery and once the modal is closed you can re-enable the save button again using jQuery. Just make sure that the jQuery event handlers are defined after btnSaveBank_Click so that btnSaveBank_Click takes precedence over the close/hide trickery:
$(document).ready(function () {
$("#btnSaveBank").click(function() {
$(this).prop("disabled", true);
$("#modBank").modal("hide");
});
$("#modBank").on("hidden.bs.modal", function() {
$("#btnSaveBank").prop("disabled", false);
});
});

client side and then server side delete

I have the following code:
<asp:Button ID="btnDelete" runat="server" Text="Delete Report" OnClientClick="return confirm ('This will delete the report. Continue?');" />
Once the user clicks on OK how do I get the server side script to fire that actually deletes.
I had
OnClick="btnDelete_Click"
on the above code but nothing
happened.
Open your code behind and add
public void btnDelete_Click(object sender, EventArgs e)
{
//Your logic here
}
You can use bootstrap's modal.
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="showDialog_Event" />
Page:
<div class="container">
<div id="modalDialog" class="modal" role="dialog">
<div class="modal-dialog modal-sm" data-backdrop="static">
<div class="modal-content">
<div class="modal-header">
<div class="modal-title text-center">
<h4>Message</h4>
</div>
</div>
<div id="modalBodyDialog" class="modal-body">
</div>
<div class="modal-footer">
<asp:Button runat="server" ID="btnOkDialog" CssClass="btn btn-default" Text="Ok" OnClick="btnOkDialog_Click" />
<input type="button" value="Cancel" data-dismiss="modal" />
</div>
</div>
</div>
</div>
Code:
public void showDialog_Event(object sender, EventArgs e) {
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(#"<script type='text/javascript'>");
sb.Append("$('#modalDialog').modal({'backdrop': 'static', 'keyboard': 'static', 'show': true});");
sb.Append("$('#modalBodyDialog').html('<ul><li>");
sb.Append(message);
sb.Append("</li></ul>')");
sb.Append(#"</script>");
Page.ClientScript.RegisterStartupScript(this.GetType(), "ModalScript", sb.ToString(), false);
}
Get event confirm (btn OK)
public void btnOkDialog(object sender, EventArgs e) {
// your code for delete
}
This example need bootstrap and jquery.

Bootstrap modal is not working as it should

I'm using a bootstrap modal to save and update some sort of events. My asp code is:
<asp:UpdatePanel ID="upModal" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional">
<ContentTemplate>
<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" id="myModal" aria-labelledby="myLargeModalLabel">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="gridSystemModalLabel">Add event:</h4>
</div>
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<div class="col-md-3">
<div class="row">
<div class="col-md-12">
<h4>Date:</h4>
</div>
<div class="col-md-12">
<asp:TextBox ID="TextBoxDate" runat="server" Width="100" CssClass="rbl"></asp:TextBox>
<asp:ImageButton ID="ImageButton2" ImageUrl="~/calendar.png" CssClass="rbl" runat="server" Height="20" Width="20" />
<ajaxToolkit:CalendarExtender ID="CalendarExtender2" TargetControlID="TextBoxDate" runat="server" PopupButtonID="ImageButton2" Format="dd/MM/yyyy" />
</div>
</div>
</div>
<div class="col-md-3">
<div class="row">
<div class="col-md-12">
<h4>List</h4>
</div>
<div class="col-md-12">
<asp:ListBox ID="ListBoxEgk" runat="server"></asp:ListBox>
</div>
</div>
</div>
<div class="col-md-3">
<div class="row">
<div class="col-md-12">
<h4>info from:</h4>
</div>
<div class="col-md-12">
<asp:TextBox ID="name" runat="server"></asp:TextBox>
</div>
<div class="col-md-12">
<h4>to:</h4>
</div>
<div class="col-md-12">
<asp:ListBox ID="ListBoxEpik" runat="server"></asp:ListBox>
</div>
</div>
</div>
<div class="col-md-3">
<div class="row">
<div class="col-md-12">
<h4>Kind of event:</h4>
</div>
<div class="col-md-12">
<asp:ListBox ID="ListBoxEidosSum" runat="server"></asp:ListBox>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-5">
<div class="col-md-12">
<h4>Event desc:</h4>
</div>
<div class="col-md-12">
<asp:TextBox ID="TextBoxSumvan" runat="server" Height="210px" MaxLength="500" Rows="12" Width="380px" TextMode="MultiLine"></asp:TextBox>
</div>
</div>
<div class="col-md-5">
<div class="col-md-12">
<h4>Actions:</h4>
</div>
<div class="col-md-12">
<asp:TextBox ID="TextBoxE" runat="server" Height="210px" MaxLength="500" Rows="12" Width="380px" TextMode="MultiLine"></asp:TextBox>
</div>
</div>
<div class="col-md-2">
<div class="col-md-12">
<h4>Given to:</h4>
</div>
<div class="col-md-12">
<asp:ListBox ID="ListBoxUsers" runat="server"></asp:ListBox>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<asp:Button ID="cancelBtn" CssClass="btn btn-default" runat="server" data-dismiss="modal" Text="Ακύρωση" OnClick="cancelBtn_Click" />
<asp:Button ID="saveBtn" runat="server" Text="Αποθήκευση" CssClass="btn btn-primary" OnClick="Btn_save_Click" />
</div>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
I'm "calling" this modal by:
img ID="addEvent" src="/very-basic-plus-icon.png" data-toggle="modal" data-target=".bs-example-modal-lg" Height="20" Width="20" />
and it works. The modal is showing up and before I used <asp:Updatepanel> it was working perfect but I want to be able to pick events from a grid and show the this modal, update them if i have to etc. The image button bellow is calling a method from behind
<asp:ImageButton ID="imgEdit" ImageUrl="~/edit.png" runat="server" OnClick="imgEdit_Click" />
and what's running from behind is:
static Boolean indexY = false;
static newEvent event4Update = new newEvent();
protected void imgEdit_Click(object sender, ImageClickEventArgs e)
{
GridViewRow gvRow = (GridViewRow)(sender as Control).Parent.Parent;
int index = gvRow.RowIndex;
var item = searchEvents.ElementAt(index);
CMMS_IServiceClient client = new CMMS_IServiceClient();
event4Update = client.returnRowForUpdate(item.RowId);
client.Close();
TextBoxDate.Text = Convert.ToString(event4Update.ImerominiaSumvantos);
name.Text = event4Update.Name;
ListBoxEgk.SelectedValue = event4Update.From;
ListBoxEpik.SelectedValue = event4Update.TroposEpikoinwnias;
UserListBox.SelectedValue = event4Update.AssignmentTo;
TextBoxSumvan.Text = event4Update.Sumvan;
ListBoxEidosSum.SelectedValue = event4Update.TypeOfEvent;
TextBoxEnergeies.Text = event4Update.Actions;
ListBoxUsers.SelectedValue = event4Update.To;
indexY = true;
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myModal", "$('#myModal').modal();", true);
upModal.Update();
}
Atm my modal is working perfect. Everything is loaded and I can edit but when I press save which is inside my modal there are problems.
protected void Btn_save_Click(object sender, EventArgs e)
{
CMMS_IServiceClient client = new CMMS_IServiceClient();
if (ListBoxEgk.SelectedValue.ToString() == "" ||
ListBoxEpik.SelectedValue.ToString() == "" ||
TextBoxSumvan.Text == "" ||
ListBoxEidosSum.SelectedValue.ToString() == "")
{
Page.ClientScript.RegisterStartupScript(GetType(), "Scripts", "<script>alert('Some field is empty.');</script>");
}
else
{
if (indexY == true)
{
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
newEvent updateEvent = new newEvent();
updateEvent.RowId = event4Update.RowId;
updateEvent.ImerominiaSumvantos = DateTime.Parse(TextBoxDate.Text, culture, System.Globalization.DateTimeStyles.AssumeLocal);
updateEvent.Name = name.Text;
updateEvent.From = ListBoxEgk.SelectedValue.ToString();
updateEvent.TroposEpikoinwnias = ListBoxEpik.SelectedValue.ToString();
updateEvent.To = UserListBox.SelectedValue.ToString();
updateEvent.Sumvan = TextBoxSumvan.Text;
updateEvent.TypeOfEvent = ListBoxEidosSum.SelectedValue.ToString();
updateEvent.Actions = TextBoxEnergeies.Text;
updateEvent.AssignmentTo = ListBoxUsers.SelectedValue.ToString();
updateEvent.EventState = (TextBoxEnergeies.Text != "") ? true : false;
client.updateRow(updateEvent);
indexY = false;
event4Update = null;
}
else
{
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
newEvent addEvent = new newEvent();
addEvent.ImerominiaSumvantos = DateTime.Parse(TextBoxDate.Text, culture, System.Globalization.DateTimeStyles.AssumeLocal);
addEvent.Name = name.Text;
addEvent.From = ListBoxEgk.SelectedValue.ToString();
addEvent.TroposEpikoinwnias = ListBoxEpik.SelectedValue.ToString();
addEvent.To = UserListBox.SelectedValue.ToString();
addEvent.Sumvan = TextBoxSumvan.Text;
addEvent.TypeOfEvent = ListBoxEidosSum.SelectedValue.ToString();
addEvent.Actions = TextBoxEnergeies.Text;
addEvent.AssignmentTo = ListBoxUsers.SelectedValue.ToString();
addEvent.EventState = (TextBoxEnergeies.Text != "") ? true : false;
client.write(addEvent);
}
client.Close();
ListBoxEgk.ClearSelection();
ListBoxEidosSum.ClearSelection();
ListBoxEpik.ClearSelection();
name.Text = "";
TextBoxEnergeies.Text = "";
TextBoxSumvan.Text = "";
TextBoxDate.Text = "";
ListBoxUsers.ClearSelection();
searchBtn_Click(sender, e);
//ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myModal", "$('#myModal').modal();", true);
//upModal.Update();
}
}
The code is also a huge mess, if anyone can suggest better ways to work with the monster i made please let me know.
Your save button has nothing to dismiss the modal. And I suspect your cancel button's data-dismiss attribute may be interering with the postback mechanism.
Try this:
<asp:Button ID="cancelBtn" CssClass="btn btn-default" runat="server" Text="Ακύρωση" OnClientClick="dismissModal();" OnClick="cancelBtn_Click" />
<asp:Button ID="saveBtn" runat="server" Text="Αποθήκευση" CssClass="btn btn-primary" OnClick="Btn_save_Click" OnClientClick="dismissModal();" />
function dismissModal() {
$('#myModal').modal('hide');
}
The OnClientClick client side method will run, then a postback will occur and your OnClick server side functions will run.

Categories