FileUpload HasFile returns false - javascript

I know that this issue is common however in my case, I'm involving a javascript so that could be the problem. Here's what I'm doing. I'm calling the asp FileUpload to allow the user to select an image. Then by calling the onchange event, I'm firing a javascript which in turn makes a hidden div become visible. The div contains a Confirm button, which then fires the upload function:
<div class="profile-page-owner-profile-pic">
<asp:FileUpload ID="profile_pic_input" onchange="profilenewimageinput(this)" runat="server"></asp:FileUpload>
</div>
Hidden Div:
<div id="profile-change-profile-pic-bg-overlay-div">
<div class="profile-change-profile-pic-bottom-bar">
<asp:Button ID="picApply" class="cropButton" runat="server" OnClick="picApply_Click" Text="Button" />
<span class="profile-page-cancel-crop-button" onclick="hideprofilepicwindow()">Cancel</span>
</div>
</div>
JS:
function profilenewimageinput() {
document.getElementById("profile-change-profile-pic-bg-overlay-div").style.display = "block";
setTimeout(function () {
document.getElementById("profile-change-profile-pic-bg-overlay-div").style.opacity = 1;
}, 100);
}
Code behind:
protected void picApply_Click(object sender, EventArgs e)
{
if (profile_pic_input.HasFile) //always returns false when debugged
{
//Code
}
}
Why is my HasFile always returning False even when an Image is selected?

Try putting it in an <asp:UpdatePanel> with an appropriate Trigger setup. The following may work, but I'm not in a place to test:
<div class="profile-page-owner-profile-pic">
<asp:UpdatePanel ID="UploadPanel" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="picApply" />
</Triggers>
<ContentTemplate>
<asp:FileUpload ID="profile_pic_input" onchange="profilenewimageinput(this)" runat="server" />
</ContentTemplate>
</UpdatePanel>
</div>

Related

jQuery with ASP.NET - Prevent Link from Scrolling to Top of Page

I am building a .NET application that uses a GridView control. I am using a LinkButton control to allow the user to enter Edit mode. Whenever the user clicks this button, it does allow him to edit an entry as it should; however, it also scrolls back to the top of the page. Obviously, this is not ideal; however, I cannot simply use event.PreventDefault() to eliminate this behavior.
I have assigned the class "gridActionLinks" to the controls. When the user clicks the need, I need the link action to occur, and then the scrolling. As it now stands, it scrolls down to the link, and then executes the default link behavior (including going to the top of the page). Is there a way around this? That is, is there a way for the link behavior to execute first, followed by the scrolling?
Thanks much!
The script:
$(".gridActionLinks").click(function (event) {
$('html, body').animate({
scrollTop: $(this).offset().top
}, 100
);
});
A snippet of the aspx:
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="detailsLink" runat="server" CommandName="Edit" CommandArgument="" Tooltip="Edit Record" CausesValidation="False" CssClass="gridActionLinks"><img src="../img/detailsIcon.png" /></asp:LinkButton>
<asp:LinkButton ID="deleteLink" CommandName="Delete" runat="server" Tooltip="Delete Record" CssClass="gridActionLinks" CausesValidation="False"><img src="../img/deleteIcon.png" /></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="insertLink" CommandName="Update" runat="server" Tooltip="Save" CausesValidation="False"><img src="../img/saveIcon.png" /></asp:LinkButton>
<asp:LinkButton ID="cancelLink" CommandName="Cancel" runat="server" Tooltip="Cancel" CausesValidation="False"><img src="../img/cancelIcon.png" /></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="insertLink" runat="server" CommandName="Insert" Tooltip="New Entry"><img src="../img/saveIcon.png" /></asp:LinkButton>
<asp:LinkButton ID="cancelLink" runat="server" CommandName="CancelEntry" Tooltip="Cancel"><img src="../img/cancelIcon.png" /></asp:LinkButton> </FooterTemplate>
</asp:TemplateField>
Some of the aspx.cs:
protected void vehicleGrid_RowEditing(object sender, GridViewEditEventArgs e)
{
vehicleGrid.EditIndex = e.NewEditIndex;
this.initialize ();
}
private void initialize()
{
try {
using (fleetModel context = new fleetModel())
{
vehicleGrid.DataSource = context.vehicles.SortBy("renewal").ToList();
vehicleGrid.DataBind();
}
} catch(Exception ex) {
Console.WriteLine(ex.StackTrace);
}
}
Since your link buttons are marked runat="server" they will generate a postback event and the page will refresh. If you wish to keep the page position after postback, use a page directive:
<%# Page Language="c#" CodeBehind="MyPage.aspx.cs" AutoEventWireup="false" Inherits="MyPage" MaintainScrollPositionOnPostBack="true"%>
or set it in code behind with
this.MaintainScrollPositionOnPostBack = true;

Asp.NET dropdown inside dialog

When clicking on an hyperlink, I create a dialog containing a dropdown (list of user) and a button. When clicking on the button, I need to retrieve the selected user.
The problem is that I can't add AutoPostBack = true on the dropdown because it will make the popup dialog disapear.
POPUP CODE
<div runat="server" id="LogonAsPopup" style="display: none;">
<div class="form">
<div class="field" style="text-align: center; margin-top: 10px;">
<ab:LabelledDropDownlist runat="server" ID="ddlUsers" DataTextField="Username" DataValueField="UserID" DataSourceID="dsUsers" Width="200px" />
<br/>
<asp:Button runat="server" ID="btLogOn" OnClick="btLogOn_OnClick" style="margin-top: 10px;" UseSubmitBehavior="False"/>
</div>
</div>
<asp:ObjectDataSource runat="server" ID="dsUsers" TypeName="Business.UserManager"
SelectMethod="GetEnabledUsersList">
</asp:ObjectDataSource>
</div>
ON CLICK
protected void btLogOn_OnClick(object sender, EventArgs e)
{
int selectedUserId = Int32.Parse(ddlUsers.SelectedValue);
}
HYPERLINK NAVIGATE URL
hl.NavigateUrl = "javascript: $('#LogonAsPopup').show(); $('#LogonAsPopup').dialog({title: '" + (String)GetGlobalResourceObject("Labels","LogonAsTitle") + "', width: 500, modal: true});";
How can I retrieve the selected item ?
Try taking out the inline style="display: none;" and instead put in the Page_Load() put
if(!IsPostBack)
{
LogonAsPopup.Attributes.Add("style","display:none");
}
This will set the display attribute to none, but only when the page first loads. Now the AutoPostBack will work as wanted
You could trigger the dialog to show again on the _SelectedIndexChanged event of the dropdown list. This is what I use:
protected void ***_SelectedIndexChanged(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:FunctionGoesHere();", true);
}

PageMethod issue with C# and uilang javascript to make placeholder Visible

I have a div box that slides into view when one of three buttons are clicked: undergrad, masters and certificates. This animation is done with uilang code (for those that don't know what uilang is you can go to uilang.com). When the button is clicked We want a list to dynamically display into the div. The list will be undergrad degrees, masters or certificates.
So the uilang slide animation is working fine. I created a separate button to test if the asp placeholder is working and it is. The list displays fine so I know there is nothing wrong with the sql or anything like that.
Here is code
// index top of page
<%# Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="online_programs" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
// form and code on index page
<form id="myform" runat="server">
<asp:ScriptManager ID="ScriptManager2" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<ContentTemplate>
<script>
function ugradList() {
PageMethods.underGradList();
}
function mList() {
PageMethods.masterList();
}
function cList() {
PageMethods.certificateList();
}
</script>
<label id="underGradButton" onclick="ugradList()" class="toggle-btn"><input type="radio" name="group3" /><i class="fa fa-circle darkgreen"> </i> Undergraduate</label>
<label id="masterButton" onclick="mList()" class="toggle-btn"><input type="radio" name="group3"/><i class="fa fa-circle darkgreen"> </i> Graduate </label>
<label id="certificateButton" onclick="cList()" class="toggle-btn"><input type="radio" name="group3"/><i class="fa fa-circle darkgreen"> </i> Certificate </label>
<asp:Label ID="PrevParentIDLabel" runat="server" Text="0" />
<div id="degree-list">
<ul><asp:PlaceHolder ID="BachelorsPlaceHolder" runat="server" Visible="false" /></ul>
<ul><asp:PlaceHolder ID="MastersPlaceHolder" runat="server" Visible="false" /></ul>
<ul><asp:PlaceHolder ID="CertificatePlaceHolder" runat="server" Visible="false" /></ul>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
// uilang code
<code>
clicking on ".toggle-btn" adds class "show-degree-results" on "#degree-results"
clicking on ".close-results" removes class "show-degree-results" on "#degree-results"
</code>
The problem I have is that when the buttons are clicked it does not display the list! I get the following logs when I inspect:
The server method 'underGradList' failed with the following error: System.NullReferenceException-- Object reference not set to an instance of an object.
The server method 'masterList' failed with the following error: System.NullReferenceException-- Object reference not set to an instance of an object.
The server method 'certificateList' failed with the following error: System.NullReferenceException-- Object reference not set to an instance of an object.
Like I said before I created a test button and pulled out one of the placeholders to test and make sure my other code is working. It worked fine. So I know I do not need help with that, but I am doing something wrong or I am missing something and I am jsut not sure what it is. Below is the C#:
public partial class online_programs : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Our sql and other code that is working fine
}
// bachelor function
[System.Web.Services.WebMethod]
public static void underGradList()
{
online_programs currentclass = new online_programs();
currentclass.MastersPlaceHolder.Visible = false;
currentclass.CertificatePlaceHolder.Visible = false;
currentclass.BachelorsPlaceHolder.Visible = true;
}
// Master function
[System.Web.Services.WebMethod]
public static void masterList()
{
online_programs currentclass = new online_programs();
currentclass.BachelorsPlaceHolder.Visible = false;
currentclass.CertificatePlaceHolder.Visible = false;
currentclass.MastersPlaceHolder.Visible = true;
}
// Certificate function
[System.Web.Services.WebMethod]
public static void certificateList()
{
online_programs currentclass = new online_programs();
currentclass.BachelorsPlaceHolder.Visible = false;
currentclass.MastersPlaceHolder.Visible = false;
currentclass.CertificatePlaceHolder.Visible = true;
}
}
I am very new to C# so if there is something missing or if you need more information please just ask. Like I said the other code is working fine. What I have provided is where the issue is. Please help!

Asp.net UserControls in datagrid using AJAX and __doPostBack

I'm using ASP.NET w/ AJAX to build a site that's similar to
http://sanjosepizzaexpress.com/order-online/
If you scroll down to the food menu, and click on a food item in the middle collumn, you see that the item expands downward to let the user to provide menu item details for ordering. There is no page reload.
I am trying to get this effect using ASP.NET w/ AJAX using Javaccript in C#. I'm having some problems.
I want to expand each individual food menu item and display item detail data from a database without a complete page reload. In my attempt (code below), the whole page is always re-loaded and every menu item is expanded every time I chick on an individual item.
My food menu is comprised of a single-collumn databound asp:datagird. Each
datagird item is a user control (OM:MnuItem) :
<asp:datagrid Runat="server">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<OM:MenuItem ID="MenuItem1" ... runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid>
MenuItem.ascx has2 divs. One div (menuItemDisplay) has the MenuItem's name, etc..
It is initially displayed in the food menu datagrid. When the user clicks on the menuItemDisplay div in the menu, the javascript DisplayItem function displays the
second div (itemDetails). MenuItem.ascx contains the UpdatePanel and ContentTemplate :
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Always" ChildrenAsTriggers="true" runat="server">
<ContentTemplate>
<div id="menuItemDisplay" onclick="DisplayDetails();">
<table >
<tr>
<td align="left" style="width:90%;">
<table >
<tr>
<td >
<asp:Label ID="nameLbl" runat="server" />
</td>
... etc ...
</tr>
</table>
<div id="itemDetails" style="visibility:hidden;" runat="server">
... item details ...
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
Javascript DisplayDetails function:
function DisplayDetails()
{
__doPostBack("DisplayDetails", "");
}
MenuItem.ascx.cs Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (Request.Form["__EVENTTARGET"] == "DisplayDetails")
{
itemDetails.Style.Value = "visibility:visible";
}
}
}
MenuItem.ascx.cs Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (Request.Form["__EVENTTARGET"] == "DisplayDetails")
{
itemDetails.Style.Value = "visibility:visible";
}
}
}
The ScriptManager is in default.aspx:
<asp:ScriptManager EnablePartialRendering="true"
ID="ScriptManager1" runat="server"></asp:ScriptManager>
Again, my problem:
The whole page is always re-loaded and every menu item is expanded every time I chick on an individual item.
Does anybody have any thoughts? Thanks for the band with.
You can use __doPostBack() to refresh an UpdatePanel, if you target the UpdatePanel itself.
This is how Dave Ward does it:
<div id="Container" onclick="__doPostBack('UpdatePanel1', '');">

Javascript in update panel doesn't work after partial postback

<script type="text/javascript">
$(function () {
$('.datePicker').datetimepicker({ dateFormat: 'dd/mm/yy' });
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:TextBox ID="TextBox1" class="datePicker" runat="server"></asp:TextBox>
<asp:UpdatePanel ID="holder" runat="server" UpdateMode="Always" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:DropDownList runat="server" ID="ddl_RespondBy" AutoPostBack="true" OnSelectedIndexChanged="ddl_SelectedIndexChanged">
<asp:ListItem Selected="True">1 Hour</asp:ListItem>
<asp:ListItem>Other</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="txt_RespondBy" class="datePicker" Visible="true" runat="server" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddl_RespondBy" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
</asp:Content>
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddl_RespondBy.SelectedItem.Text == "Other")
{
txt_RespondBy.Visible = true;
}
else
{
}
}
I do partial post back with the update panel, I have two text box one outside update panel and one inside, when I select other from the dropdown and try to open the calendar inside the txt_RespondBy text box it doesn't show, but the text box outside update panel shows the calendar. why is Javascript not working inside update panel after partial postback
Place your datetimepicker initialisation code in the pageLoad function, which is called whenever the page loads (asynchronously or synchronously).
<script type="text/javascript">
function pageLoad(sender, args) {
$('.datePicker').datetimepicker({ dateFormat: 'dd/mm/yy' });
}
</script>
You can use pageLoad or .live:
Reference info:
$(document).ready() and pageLoad() are not the same
.live:
Jquery .live works but not with .datepicker
$(function(){
$('.datePicker').live('click', function() {
$(this).datepicker({showOn:'focus'}).focus();
});
});
pageLoad():
function pageLoad(sender, args) {
$('.datePicker').datetimepicker({ dateFormat: 'dd/mm/yy' });
}
I understand this is a old question but then also I am posting one more answer here if someone visit this page now or in later times for help.
one can use
$(document).on()
as it makes sure that controls bind to the events whenever page loads. Its job is Similar to page load event but you can say syntax is different. And almost for anything and everything this works. I have more than 50 controls in a panel and all to perform different task and I never got into trouble.. not even once as i was using this function.
$(document).on('eventName', 'element' , function(){
//your code to perform some task;
});
eventName can be any event - like click, change, select..
And
Element - can be a name, classname, id
example - as above question -
html -
<script src="lib/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
<input type="text" class="datePicker" data-provide="datepicker-inline" data-date-format="mm/dd/yyyy">
Javascript -
$(function(){
$(document).on('click', '.datePicker' , function(){
$(this).datepicker();
});
});

Categories

Resources