Evening all I'm trying to create a page that will pull locations from a database and display it within a a gridview, this gridview then dictates some points that appear on a Google maps element. It works fine on start up but when I use the text box to refine the items in gridview the map disappears. I'm guessing it's an issue with my ScriptManager but I'm unsure exactly what the cause is. Any ideas would be greatly appreciated. Apologies for the wall of code I'm just a bit unsure what might be relevant at this stage.
<%# Page Title="" Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MapTest.Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script type="text/javascript">
function RefreshUpdatePanel() {
__doPostBack('<%= txtSearch.ClientID %>', '');
};
</script>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyA5U97yznzCvzDaUZjT3AydlQqyFBQVYc8&sensor=false">
</script>
<link href="App_Themes/Default/default.css" rel="stylesheet" type="text/css" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="Wrapper">
<asp:ScriptManager ID="MasterScriptManger" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="upanSearch" runat="server" UpdateMode="Conditional" OnPreRender="upanSearch_PreRender">
<ContentTemplate>
<div class="DataTable">
<span>Search</span>
<asp:TextBox ID="txtSearch" runat="server" onkeyup="RefreshUpdatePanel();" onfocus="this.value = this.value;" OnTextChanged="txtSearch_TextChanged" AutoPostBack="True" AutoCompleteType="Disabled"></asp:TextBox>
<asp:GridView ID="grdLocations" runat="server" AutoGenerateColumns="False" DataSourceID="sqldsLocations">
<AlternatingRowStyle BackColor="#F6F6F6" />
<Columns>
<asp:BoundField DataField="Location Name" HeaderText="Location Name" SortExpression="Location Name" />
<asp:BoundField DataField="Latitude" HeaderText="Latitude" SortExpression="Latitude" />
<asp:BoundField DataField="Longitude" HeaderText="Longitude" SortExpression="Longitude" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sqldsLocations" runat="server" ConnectionString="<%$ ConnectionStrings:MapTestGuestConn %>" SelectCommand="GetLocations(mySearch)" CancelSelectOnNullParameter="False" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="txtSearch" Name="mySearch" PropertyName="Text" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</div>
<div id="googleMap" style="width:500px;height:380px;"></div>
<script type="text/javascript">
initializeMap();
</script>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtSearch" EventName="TextChanged"/>
</Triggers>
</asp:UpdatePanel>
</div>
</asp:Content>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows;
namespace MapTest
{
public partial class Default : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
Page.Theme = "Default";
}
protected void upanSearch_PreRender(object sender, EventArgs e)
{
//MessageBox.Show(BuildMapScript());
ScriptManager.RegisterClientScriptBlock(upanSearch, upanSearch.GetType(), "BuildMap", BuildMapScript(), false);
//ScriptManager.RegisterStartupScript(upanSearch, upanSearch.GetType(), "BuildMap", BuildMapScript(), false);
}
protected void txtSearch_TextChanged(object sender, EventArgs e)
{
txtSearch.Focus();
}
protected string BuildMapScript()
{
grdLocations.DataBind();
string markers = GetMarkers();
string myScript = #"
<script type='text/javascript'>
function initializeMap() {
var mapOptions = {
center: new google.maps.LatLng(50.826108, -1.075011),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var myMap = new google.maps.Map(document.getElementById('googleMap'),
mapOptions);"
+ markers +
#"}
</script>";
return myScript;
}
protected string GetMarkers()
{
string markers = "";
int c = 1;
foreach (GridViewRow grdRow in grdLocations.Rows)
{
markers +=
#"var marker" + c + #" = new google.maps.Marker({
position: new google.maps.LatLng(" + grdRow.Cells[1].Text.ToString() + ", " +
grdRow.Cells[2].Text.ToString() + ")," +
#"map: myMap,
title:'" + grdRow.Cells[0].Text.ToString() + "'});";
c++;
}
return markers;
}
}
}
The updatepanel updating would cause the issue you experience. You would need to reinitialize the google map on postback if within the updatepanel... to do that you can attach to Sys.Application's endRequest event, which fires when the updatepanel finishes, and reinitialize the map. Or pull the map out of the updatepanel.
Related
I'm hoping someone can help me as I'm beating my head against a wall trying to figure out the problem. I have a databound CheckboxList that has the SelectedIndexChanged event wired up. AutoPostBack is equal to true and ViewStateMode and EnableViewState are set to "Enabled" and "True" respectively. I have other controls on this same page with server side events that fire just fine with no issue.
The weird thing is, the event SEEMS to be firing, as I can see the page reload when I check one of the items in the list. However, when I set a debug point on the method, the debugger never breaks into that section and none of my code is firing (I've even tried having it write out silly messages just to see if the method is even firing - it's not). Here's the markup:
<asp:CheckBoxList id="chkLanguages" runat="server" AutoPostBack="true" ViewStateMode="Enabled" EnableViewState="true" data-paramname="lcid"
OnSelectedIndexChanged="chkLanguages_SelectedIndexChanged" />
Here's the SelectedIndexChanged event:
protected void chkLanguages_SelectedIndexChanged(object sender, EventArgs e)
{
//Do all the things
}
What am I missing? I feel like it must be something obvious but for the life of me, I can't see it.
Also I should note this is in the latest version of Mono so there might be some weird quirk there that's causing the issue.
One final note, there are no errors in the console if I check the browser developer tools so I don't have any weird javascript stuff going on that's causing an issue.
Update
Since it's been asked, I'm posting the entire page markup and the requisite codebehind.
Markup:
<%# Page Language="C#" MasterPageFile="~/pages/master/main.master" Inherits="Letters.Web.UI.searchLetters" AutoEventWireup="true" %>
<asp:Content runat="server" ContentPlaceHolderID="additionalCSS">
<link rel="stylesheet" type="text/css" href="<%= Page.ResolveClientUrl("~/resources/css/letters.css") %>" />
<link rel="stylesheet" type="text/css" href="<%= Page.ResolveClientUrl("~/resources/css/font-awesome.min.css") %>" />
<link rel="stylesheet" type="text/css" href="<%= Page.ResolveClientUrl("~/resources/css/bootstrap.css") %>" />
<link rel="stylesheet" type="text/css" href="<%= Page.ResolveClientUrl("~/resources/css/bootstrap-multiselect.css") %>" />
</asp:Content>
<asp:Content runat="server" ContentPlaceHolderID="additionalJS">
<script type="text/javascript"
src="<%= Page.ResolveClientUrl("~/resources/javascript/bootstrap.min.js") %>">
</script>
<script type="text/javascript"
src="<%= Page.ResolveClientUrl("~/resources/javascript/bootstrap-multiselect.js") %>">
</script>
</asp:Content>
<asp:Content runat="server" ContentPlaceHolderID="mainContent">
<section id="search-header">
<div class="column">
<div class="field-set">
<asp:Label id="lblTextString" runat="server" CssClass="data-label">Search for Letters</asp:Label>
<div class="data-control">
<asp:TextBox id="txtTextString" Width="100%" runat="server" CssClass="form-control searchable" placeholder="Contains Text" data-paramname="textString" />
</div>
</div>
</div>
<div class="column-small">
<div class="field-set">
<span class="data-label"> </span>
<div class="data-control">
<button id="btnSearch" runat="server" class="search-nav-buttons" onserverclick="Search_Click">
Search
</button>
</div>
</div>
</div>
</section>
<asp:PlaceHolder id="plcSearchResults" runat="server">
<section id="search-results">
<div class="filter-options">
<table>
<tbody>
<tr class="searchresults-headerstyle">
<th scope="col" class="header">Filter Options</th>
</tr>
</tbody>
</table>
<asp:Panel id="pnlLanguage" runat="server">
<h1>Languages</h1>
<asp:HiddenField id="hdlLanguages" runat="server" />
<asp:CheckBoxList id="chkLanguages" runat="server" AutoPostBack="true" ViewStateMode="Enabled" EnableViewState="true" data-paramname="lcid"
OnSelectedIndexChanged="chkLanguages_SelectedIndexChanged" />
</asp:Panel>
</div>
<asp:GridView id="grvResults" runat="server" CssClass="table table-striped table-bordered" AutoGenerateColumns="false"
AllowPaging="true" AllowSorting="true" Width="70%" GridLines="None"
OnPageIndexChanging="GridView_PageIndexChanging" >
<HeaderStyle CssClass="searchresults-headerstyle" />
<FooterStyle CssClass="searchresults-footerstyle" />
<PagerStyle CssClass="pagination-style" />
<Columns>
<asp:TemplateField HeaderText="Search Results" >
<ItemTemplate>
<div class="search-result-record">
<asp:HyperLink runat="server" NavigateUrl='<%# Eval("LetterUrl") %>' Text='<%# Letters.Tools.WebUtils.HtmlEncode(Eval("Title").ToString()) %>' />
<span>(<%# Eval("Language") %>)</span>
<span class="keywords">Keywords: <%# Eval("Categories") %></span>
<asp:Label runat="server" CssClss="language" Visible='<%# Eval("LCID").ToString() != "en" %>'>Language: <%# Eval("Language") %></asp:Label>
<div class="search-abstract">
<%# Eval("SearchAbstract") %>
</div>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</section>
</asp:PlaceHolder>
</asp:Content>
Code Behind:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using Letters.Domain.Objects;
using Letters.Tools;
namespace Letters.Web.UI
{
public partial class searchLetters : System.Web.UI.Page
{
#region eventhandlers
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack) {
this.BindResults ();
}
}
protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.grvResults.PageIndex = e.NewPageIndex;
this.BindResults ();
}
protected void chkLanguages_SelectedIndexChanged(object sender, EventArgs e)
{
this.hdlLanguages.Value = this.GetSelectedItems (this.chkLanguages);
this.FilterResults ();
}
protected void Search_Click(object sender, EventArgs e)
{
Dictionary<string, object> parameters = new Dictionary<string, object> ();
if (!string.IsNullOrEmpty (this.txtTextString.Text))
parameters.Add (this.txtTextString.Attributes ["data-paramname"].ToString (), this.txtTextString.Text);
this.BindResults (parameters);
}
#endregion
private void FilterResults()
{
Dictionary<string, object> parameters = new Dictionary<string, object> ();
if (pnlLanguage.Visible) {
parameters.Add (this.chkLanguages.Attributes ["data-paramname"].ToString (), this.GetSelectedItems (this.chkLanguages));
}
//Finally, add the search string
if (!string.IsNullOrEmpty (this.txtTextString.Text))
parameters.Add (this.txtTextString.Attributes ["data-paramname"].ToString (), this.txtTextString.Text);
this.BindResults (parameters);
}
private string[] GetFilterOption(string delimitedValue)
{
string[] result = null;
if (delimitedValue.Contains (",")) {
result = delimitedValue.Split (new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
} else
result = new string[] { delimitedValue };
return result;
}
private string GetSelectedItems(CheckBoxList list)
{
StringBuilder result = new StringBuilder ();
foreach (ListItem item in list.Items) {
if (item.Selected)
result.Append (item.Value).Append (",");
}
if (result.Length > 0) {
result.Remove (result.Length - 1, 1);
return result.ToString ();
}
else
return null;
}
private string GetSelectedItems(ListBox list)
{
StringBuilder result = new StringBuilder ();
foreach (ListItem item in list.Items) {
if (item.Selected)
result.Append (item.Value).Append (",");
}
if (result.Length > 0) {
result.Remove (result.Length - 1, 1);
return result.ToString ();
}
else
return null;
}
private void PopulateFilters(List<SearchResult> results)
{
var languages = (from x in results
group x by new { x.LCID, x.Language } into counts
select new { Key = counts.Key.LCID, DisplayName = string.Format("{0} ({1})", counts.Key.Language, counts.Count()) }
).ToList();
this.chkLanguages.DataSource = languages;
this.chkLanguages.DataTextField = "DisplayName";
this.chkLanguages.DataValueField = "Key";
this.chkLanguages.DataBind ();
if (!string.IsNullOrEmpty (hdlLanguages.Value)) {
string[] languageSelect = this.GetFilterOption (hdlLanguages.Value);
foreach (ListItem item in this.chkLanguages.Items) {
if (languageSelect.Contains (item.Value))
item.Selected = true;
}
}
}
private void BindResults()
{
List<SearchResult> results = this.GetSearchResults ();
this.grvResults.DataSource = results;
this.grvResults.DataBind ();
this.PopulateFilters (results);
}
private void BindResults(Dictionary<string, object> parameters)
{
List<SearchResult> results = this.GetSearchResults(parameters);
this.grvResults.DataSource = results;
this.grvResults.DataBind ();
this.PopulateFilters (results);
}
private void RegisterEvents()
{
this.grvResults.PageIndexChanging += new System.Web.UI.WebControls.GridViewPageEventHandler (GridView_PageIndexChanging);
}
private List<SearchResult> GetSearchResults()
{
return LetterService.GetSearchResults ();
}
private List<SearchResult> GetSearchResults(Dictionary<string, object> parameters)
{
return LetterService.GetSearchResults (parameters);
}
}
}
I was never able to find the exact cause to the problem. Every other type of control was able to post back events and I could properly handle their events server-side. I ended up working around this particular issue by ripping out the CheckBoxList and replacing it with a gridview that used an item template to store the value in a hidden field and display the checkbox where I could then handle the OnCheckedChanged event (see code below). This worked brilliantly.
Markup
<asp:GridView id="grvLanguages" runat="server" ShowHeader="false" ShowFooter="false" AllowPaging="false"
AllowSorting="false" GridLines="None" AutoGenerateColumns="false" data-paramname="languages" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField id="hdlValue" runat="server" Value='<%# Eval("Key") %>' />
<asp:CheckBox id="chkDisplay" runat="server" Text='<%# Eval("DisplayName") %>' OnCheckedChanged="chkLanguage_SelectedIndexChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind
protected void chkLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
this.hdlLanguages.Value = this.GetSelectedItems (this.grvLanguages);
this.FilterResults ();
}
I'm guessing the problem is probably some weird, esoteric bug in the Mono framework. Like I said, I don't have a problem with ANY other controls (I tested quite a few - all of their server side events handled just fine); it was just a problem with the CheckBoxList.
At my Production.aspx Web Form I have this code:
<%# Page Title="" Language="C#" MasterPageFile="~/Index.Master" AutoEventWireup="true" CodeBehind="Production.aspx.cs" Inherits="WebPortal.Production" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<h3>PRODUCTION SITE</h3>
<img src="" alt="Production Logo" height="350" width="350" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
<asp:Login ID="Login1" runat="server" BackColor="#F7F7DE" BorderColor="#CCCC99" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="10pt" Height="187px" Width="235px">
<TitleTextStyle BackColor="#6B696B" Font-Bold="True" ForeColor="#FFFFFF" />
</asp:Login>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder3" runat="server">
</asp:Content>
And at my Production.aspx.cs Web Form i Have this Code:
namespace WebPortal
{
public partial class Production : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
var GetSession = Session["Counter"];
if (Convert.ToInt32(GetSession) == 1)
{
// Show Content 1
}
else if (Convert.ToInt32(GetSession) == 2)
{
// Show Content 2
}
else
{
// Show Content 3
}
}
catch (Exception ex)
{
// MessageBox.show(ex.message.tostring());
}
}
}
}
how can i try to hide a content based on the session value like when a user try to login by its account and based on its access level he gets a 1 which trigger the if statement then based on its value on what content to show..
Put div into every content and show/hide div like folowing:
ASPX:
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div runat="server" id="div1">
<h3>PRODUCTION SITE</h3>
<img src="" alt="Production Logo" height="350" width="350" />
</div>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
<div runat="server" id="div2">
<asp:Login ID="Login1" runat="server" BackColor="#F7F7DE" BorderColor="#CCCC99" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="10pt" Height="187px" Width="235px">
<TitleTextStyle BackColor="#6B696B" Font-Bold="True" ForeColor="#FFFFFF" />
</asp:Login>
</div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder3" runat="server">
<div runat="server" id="div3">
<p>q3</p>
</div>
</asp:Content>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
div1.Visible = div2.Visible = div3.Visible = false;
if (Session["Counter"] != null)
{
int GetSession = (int)Session["Counter"];
if (GetSession == 1)
div1.Visible = true;
else if (GetSession == 2)
div2.Visible = true;
else
div3.Visible = true;
}
else
div3.Visible = true;
}
You're probably best using different nested master pages for different access levels as suggested above, though if you're stuck with what you've got you could use a multiview control on the master with three views, each holding one of the placeholders.
Add a MasterType directive to your content pages so you can reference the Master page then set the Multiview active index as required.
Code is not tested, just a rough idea - I'd use a switch block instead of 'if' myself.
protected void Page_Load(object sender, EventArgs e)
{
MultiView mv = (MultiView)Master.FindControl("multiView1");
var GetSession = Session["Counter"];
if (Convert.ToInt32(GetSession) == 1)
{
mv.ActiveViewIndex = 0
}
else if (Convert.ToInt32(GetSession) == 2)
{
mv.ActiveViewIndex = 1
}
else
{
mv.ActiveViewIndex = 2
}
}
I'm trying to get gridview data using jquery. I have modified existing data on textbox and try to get that value using jquery. but it gave old value in textbox. not modified value in textbox.
ASPX Code
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
/*javascripts and stylesheets are here*/
<script type="text/javascript">
function Navigate() {
$('#dialogDiv').dialog('open');
}
$(document).ready(function () {
var list = "";
$('#dialogDiv').dialog({
autoOpen: false,
resizable: true,
width: 300,
height: 'auto',
buttons: {
"Save": function () {
$("#<%=Type_GV.ClientID %> tr").each(function () {
//Skip first(header) row
if (!this.rowIndex) return;
var type = $(this).find("td:last").html();
list += type + "</br>";
});
alert(list)
}
}
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<div id="dialogDiv" title="Type" style="overflow: hidden">
<div id="TypeDiv" class="divTable">
<div class="divRow">
<div class="divColumn">
<div>
<asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="open" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:GridView ID="Type_GV" runat="server" ShowFooter="True" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Type">
<ItemTemplate>
<asp:TextBox ID="txtType" runat="server" Text='<%# Bind("Type") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
</div>
</div>
</div>
<asp:Button ID="open" runat="server" Text="Open dialog" OnClientClick="Navigate()"
OnClick="open_Clicked" />
<br />
<p>
<asp:Button ID="btnSaveType" runat="server" OnClick="btnSaveType_Clicked" Style="visibility: hidden;
display: none;" />
</p>
</asp:Content>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
}
protected void open_Clicked(object sender, EventArgs e)
{
VehicleType vTypeObject = new VehicleType();
Type_GV.DataSource = vTypeObject.GetTypeList();
Type_GV.DataBind();
}
protected void btnSaveType_Clicked(object sender, EventArgs e)
{
foreach (GridViewRow gvr in Type_GV.Rows)
{
TextBox type = (TextBox)gvr.FindControl("txtType");
Debug.WriteLine("type : " + type.Text);
}
}
public class VehicleType
{
public string Type { get; set; }
public List<VehicleType> GetTypeList()
{
List<VehicleType> list = new List<VehicleType>()
{
new VehicleType{Type="Type1"},
new VehicleType{Type="Type2"}
};
return list;
}
}
How can i solve this ?
You may use this:
As you are using the update panels, this.remove_endRequest() is raised after an asynchronous postback is finished and control has been returned to the browser.
Not sure but i think this the issue, i faced these kind of issues many times. Might be helpful to you.
See Documentation
Sys.WebForms.PageRequestManager.getInstance().remove_endRequest($(function(){
var list = "";
$('#dialogDiv').dialog({
autoOpen: false,
resizable: true,
width: 300,
height: 'auto',
buttons: {
"Save": function () {
$("#<%=Type_GV.ClientID %> tr").each(function () {
//Skip first(header) row
if (!this.rowIndex) return;
var type = $(this).find("td:last").html();
list += type + "</br>";
});
alert(list)
}
}
});
});)
Note: Don't remove $(document).ready(function{})) keep it as it is, and include this one.
I have a very simple ASP.NET page that uploads an Excel workbook, then processes it. It uses AJAXFILEUPLOAD from the AJAX toolkit on ASP.NET... Here's the markup:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="ImportWorkbook.aspx.cs" Inherits="Timesheet.ImportWorkbook" %>
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="HeaderContentPlaceHolder">
<h1 class="topContent">
Upload CPAS Timesheet Workbooks
</h1>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="RightContentPlaceHolder" runat="server">
<br />
<br />
<asp:HiddenField ID="tbTSID" runat="server" />
<asp:HiddenField ID="tbWorkbookPath" runat="server" />
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server" AllowedFileTypes="xls,xlsx,xlsm"
CssClass="dropdown" MaximumNumberOfFiles="1" OnUploadComplete="AjaxFileUpload1_UploadComplete" />
<br />
<br />
<asp:Panel ID="ProcessChoices" runat="server" >
<br />
<br />
<p>
Select how you want this workbook processed:</p>
<br />
<asp:RadioButtonList ID="rbChoices" runat="server" BorderStyle="Groove" BorderWidth="2px"
BorderColor="Black" BackColor="Teal" Font-Names="Tahoma" Font-Size="10pt" ForeColor="White"
Width="40%">
<asp:ListItem Value="True" Selected="True">  Replace ALL Items in the Timesheet</asp:ListItem>
<asp:ListItem Value="False">  Add Items from this Workbook to the Existing Timesheet Items</asp:ListItem>
</asp:RadioButtonList>
<br />
<br />
<asp:Button ID="btnValidate" runat="server" Text="Validate and Process"
BackColor="#B92217" ForeColor="White" BorderColor="#7C1810"
BorderStyle="Groove" Font-Names="Tahoma" onclick="btnValidate_Click" />
</asp:Panel>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="BottomSpanContentPlaceHolder" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</asp:Content>
The master page and css pages are trivial, formatting only.
Here's the codebehind:
using System;
using System.IO;
using TimesheetUtilites;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
namespace Timesheet
{
public partial class ImportWorkbook : System.Web.UI.Page
{
private const string HDriveLocation= "H:\\mtv\\secure\\Construction\\Access\\CPAS WorkArea\\TimesheetUploads\\";
private string strWorkbookPath;
private int currTSID;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.QueryString["ID"] != null)
{
tbTSID.Value = Request.QueryString["ID"]; // Storing the Timesheet ID in a hidden Textbox
}
}
else
{
if (!string.IsNullOrEmpty(tbWorkbookPath.Value))
{
ProcessChoices.Enabled = true;
}
}
int.TryParse(tbTSID.Value, out currTSID);
strWorkbookPath = tbWorkbookPath.Value;
}
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxFileUploadEventArgs e)
{
strWorkbookPath = HDriveLocation + Path.GetFileName(e.FileName);
tbWorkbookPath.Value = strWorkbookPath;
AjaxFileUpload1.SaveAs(strWorkbookPath);
ProcessChoices.Enabled = true;
}
protected void btnValidate_Click(object sender, EventArgs e)
{
bool processOption;
bool.TryParse(rbChoices.SelectedValue, out processOption);
strWorkbookPath = tbWorkbookPath.Value;
TimesheetUtilites.ImportTimesheet imp = new ImportTimesheet(currTSID, strWorkbookPath, processOption);
}
}
}
My issue is simple. Although the event handler "AjaxFileUpload1_UploadComplete" works fine, and uploads the file in an instant, when I fire the "btnValidate_Click" event, the "tbWorkbookPath.Value" has become an empty string, and the "ProcessChoices.Enabled" propety doesn't change. Needless to say, the "Upload Complete" event handler is the only opportunity I have to capture this file path, so I'm at a loss what I'm doing wrong.
I posted on ASP.NET and go NO answers. Can anyone give me an idea where to start?
This is information you should be storing in your page's ViewState so that it persists between postbacks and resets on page initialization. Change your private string member to something like the following:
private string strWorkbookPath {
get {
return this.ViewState["strWorkbookPath"];
}
set {
this.ViewState["strWorkbookPath"] = value;
}
}
If you need a primer on what the ViewState is, check out this article on MSDN: Saving Web Forms Page Values Using View State. It's a bit dated but still communicates the basics of how ViewState operates currently.
Put a hidden field with runat="server" attribute on your page and use the below script:
<script type="text/javascript">
function uploadComplete(sender, args) {
var filename = args.get_fileName();
$("#hiddden_field_id").val(filename);
}
</script>
Now you should be getting the image name in your events.
I think you should try storing that value in session rather than a hidden field as the page is not reloaded and it was an ajax call. So when the button is clicked for validation, it is actually another request made but the value of the hidden field in this page object and the hidden field is still empty. Once your job is done for that value in session, remove it from there or set it to some different value.
I am using Google ReCaptcha V2 and it is inside an updatepanel. IF validation failed ReCaptcha disappears on postback.
I read similar topics but I have not yet found an answer that solves my problem.
Please help!
My ASPX code :
<%# Register Assembly="GoogleReCaptcha" Namespace="GoogleReCaptcha" TagPrefix="cc1" %>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<form id="formRegister" runat="server">
<asp:ScriptManager ID="ScriptManagerRegister" EnablePartialRendering="true" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanelRegister" hildrenAsTriggers="false" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
<asp:Button ID="ButtonRegister" runat="server" Text="Registrera" CssClass="btn btn-primary btn-md" /><br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</asp:Content>
My code behind C#
GoogleReCaptcha.GoogleReCaptcha ctrlGoogleReCaptcha = new GoogleReCaptcha.GoogleReCaptcha();
protected override void CreateChildControls()
{
base.CreateChildControls();
ctrlGoogleReCaptcha.PublicKey = "My Public Key";
ctrlGoogleReCaptcha.PrivateKey = "My Private Key";
this.Panel1.Controls.Add(ctrlGoogleReCaptcha);
}
protected void Page_Load(object sender, EventArgs e)
{
ButtonRegister.Click += new EventHandler(ButtonRegister_Click);
}
protected void ButtonRegister_Click(object sender, EventArgs e)
{
if (ctrlGoogleReCaptcha.Validate())
{
//submit form
Label1.Text = "Success";
}
else
{
Label1.Text = "Captcha Failed!! Please try again!!";
}
}
use this script after body
<body>
<script language="javascript" type="text/javascript">
function pageLoad()
{
$('.g-recaptcha').each(function (index, obj) {
grecaptcha.render(obj, { 'sitekey': 'yoursitekey' });
});
}
</script>