How can i handle Jquery tab close in codebehind - c#

i use jquery tabs.
<%# register src="~/UserControls/Order/Control/OrderProductLicense.ascx" tagname="OrderProductLicense" tagprefix="uc1" %>
<script type="text/javascript">
$(function() {
$("#tabs").tabs({
closable: true,
cache: true,
show: function() {
var selectedTab = $('#tabs').tabs('option', 'selected');
$("#<%= hdnSelectedTab.ClientID %>").val(selectedTab);
},
selected: <%= hdnSelectedTab.Value %>
});
});
</script>
<table width="100%">
<tr>
<td>
<div id="tabs">
<ul>
<asp:Repeater ID="rptTabs" runat="server">
<ItemTemplate>
<li><a href="#tabs-<%#DataBinder.Eval(Container,"ItemIndex","") %>">
<%#Eval("Id") %></a></li>
</ItemTemplate>
</asp:Repeater>
</ul>
<asp:Repeater ID="rptTabsSub" runat="server">
<ItemTemplate>
<div id="tabs-<%# DataBinder.Eval(Container, "ItemIndex", "") %>">
<uc1:OrderProductLicense ID="OrderProductLicense1" runat="server" />
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<asp:HiddenField ID="hdnSelectedTab" runat="server" Value="0" />
</td>
</tr>
</table>
My tabs has got close button. But i want to when a person close my tab after i want to delete some data in my session list with my selected tab text. Forexample.
public void TabClosing(object sender, string tabText)
{
MySession.OrderProductIdList.RemoveAll(p => p.ItemText == tabText);
}
how can write code like this ?
Best Regards

Markup:
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#tabs").tabs({
});
$("#tabs span.ui-icon-close").on("click", function () {
var itemId = $(this).data().id;
$(this).closest("li").remove();
$("#tabs-" + itemId).remove();
$("#tabs").tabs("refresh");
$.ajax({
url: '<%= ResolveClientUrl("~/WebForm1.aspx/DeleteRecord") %>',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ id: itemId })
});
});
});
</script>
<div id="tabs">
<ul>
<asp:Repeater runat="server" ID="rptTabs">
<ItemTemplate>
<li><a href='<%# Eval("ID", "#tabs-{0}") %>'>
<%# Eval("Title") %></a> <span class="ui-icon ui-icon-close" data-id='<%# Eval("ID") %>'>Remove Tab</span>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
<asp:Repeater runat="server" ID="rptTabsSub">
<ItemTemplate>
<div id='<%# Eval("ID", "tabs-{0}") %>'>
<%# Eval("Content") %>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var dataSource = (from id in Enumerable.Range(0, 10)
select new { ID = id, Title = id.ToString() + " Title", Content = Guid.NewGuid().ToString() }).ToList();
rptTabs.DataSource = dataSource;
rptTabs.DataBind();
rptTabsSub.DataSource = dataSource;
rptTabsSub.DataBind();
}
}
[WebMethod]
public static void DeleteRecord(int id)
{
//delete record by id
}

Set EnablePageMethods = true in scriptmanager
<input type="button" id="btnClose" value="Close" onclick="DeleteEntryFromSession();"/>
//javascript
function DeleteEntryFromSession()
{
PageMethods.DeleteSessionEntry(para1,function(result)
{
//Success
//your closing code comes here
} ,function(error){ //error});
}
//c#
[WebMetod]
public static string DeleteSessionEntry(string para1)
{
try
{
// HttpContext.Current.Session["sessionName"]; //To Get session
//Delete Entry from Session
return "true"
}
catch(Exception)
{
throw;
}
}

Related

Load Additional Data While scrolling down a page using jQuery Ajax and ASP.NET

I am trying to apply the captioned feature in my project and decided to try it out to see how it works. But while testing it, it shows an Client script error with a message Undefined when I scroll to the bottom of the page. I do not know what I did wrong in my code and I don't know how to get it to work. I am hoping someone helps me out of this. Below is the code:
Repeater
<div id="dvCampaigns">
<asp:Repeater ID="rptUsers" runat="server">
<ItemTemplate>
<table cellpadding="2" cellspacing="0" border="1" style="width: 200px; height: 100px;
border: dashed 2px #04AFEF; background-color: #B0E2F5">
<tr>
<td>
<b><u><span class="campaignname">
<%# Eval("CampaignName") %></span></u></b>
</td>
</tr>
<tr>
<td>
<b>Description: </b><span class="description">
<%# Eval("Description") %></span><br />
<b>ID: </b><span class="campaign-id">
<%# Eval("CampaignID") %></span><br />
<b>Date Created: </b><span class="datecreated">
<%# Eval("CreatedOn")%></span><br />
</td>
</tr>
</table>
<br />
</ItemTemplate>
</asp:Repeater>
</div>
<div>
<img id="loader" alt="" src="../Images/loading.gif" style="display: none" />
</div>
Code-Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
rptCampaigns.DataSource = GetUserData(1);
rptCampaigns.DataBind();
}
}
public static TList<POLLice.Entities.Campaigns> GetCampaignData(int pageIndex)
{
int totalData;
var items = new CampaignsService().GetAll(pageIndex, 10, out totalData);
return items;
}
[WebMethod]
public static string GetCampaigns(int pageIndex)
{
var dataset = GetUserData(pageIndex).ToDataSet(true);
return dataset.GetXml();
}
jQuery Script
<script type="text/javascript">
var pageIndex = 1;
var pageCount;
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
GetRecords();
}
});
function GetRecords() {
pageIndex++;
if (pageIndex == 2 || pageIndex <= pageCount) {
$("#loader").show();
$.ajax({
type: "POST",
url: "UserProfile/Default.aspx/GetCampaigns",
data: '{pageIndex: ' + pageIndex + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
},
error: function(response) {
alert(response.d);
}
});
}
}
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
var campaigns = xml.find("Campaigns");
campaigns.each(function() {
var campaign = $(this);
var table = $("#dvCampaigns table").eq(0).clone(true);
$(".campaignname", table).html(campaign.find("CampaignName").text());
$(".description", table).html(campaign.find("Description").text());
$(".campaign-id", table).html(campaign.find("CampaignID").text());
$(".datecreated", table).html(campaign.find("CreatedOn").text());
$("#dvCampaigns").append(table).append("<br />");
});
$("#loader").hide();
}
</script>
Many Thanks.
In your ajax you have this line:
url: "UserProfile/Default.aspx/GetCampaigns",
Did you remove the full path including http for this post or is that the way it is in your code? That needs a relative or absolute path to the web method. Also when calling web methods with ajax you need to use:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] //or whatever your return format is
[WebMethod]

Pagemethods in popuppanel does not load the second time in IE9

I have a main page which has some pagemethod called to perform some activities. A popuppanel(popuppanel content page also have pagemethods) is used within this main page to show some details. If the same is executed multiple times (i.e., opening the popup panel many times), it is working in all other browsers other than IE9 (working even in IE8). However, first time execution is successful. The code that is being used is provided below.
Scriptmanager used as follow:
<ajaxToolkit:ToolkitScriptManager runat="server" ID="TSCM1" EnablePageMethods="true" />
Script In Main Page:
function Clkd(){
var ppnl=document.getElementById("if1");
ppnl.src="Test1.aspx";
$find('<%= MPE.ClientID %>').show();
}
function Clkd2(){
var ppnl=document.getElementById("if1");
ppnl.src="";
$find('<%= MPE.ClientID %>').hide();
}
$(document).ready(function(){
PageMethods.mainPageMethod("MainTest",cbackfn);
});
function cbackfn(str){
alert(str);
}
Page method:
[System.Web.Services.WebMethod(EnableSession = true)]
public static string mainPageMethod(String mainStr)
{
return mainStr + " Ok";
}
Test1.aspx page Details (this is the page loaded inside the popup panel):
Script code below :
$(document).ready(function(){
PageMethods.Testpm("Test",fnd);
});
function fnd(str){
alert(str);
}
Page method:
[System.Web.Services.WebMethod(EnableSession = true)]
public static string Testpm(String alrt)
{
return "Ok";
}
The following error is thrown if the same is executed the second time (in IE9 only)
SCRIPT5007: Unable to set value of the property '_UpdateProgress': object is null or undefined
ScriptResource.axd?........
SCRIPT5007: Unable to get value of the property 'WebServiceProxy': object is null or undefined
Test1.aspx, line 66 character 1
SCRIPT5007: Unable to get value of the property 'DomElement': object is null or undefined
ScriptResource.axd?......, line 2 character 18851
SCRIPT5007: Unable to get value of the property 'add_init': object is null or undefined
Test1.aspx, line 97 character 122
SCRIPT438: Object doesn't support property or method 'Testpm'
Test1.aspx, line 11 character 4
Important Note: if main page does not have any pagemethods then its working fine.
please help me out from this issue..
You should have added relevant HTML, that might have helped others to help you out.
Well I used your code and added missing code and when I runt it, it is working fine in all browsers including IE9.
Please find below code:
Main Page (Default.aspx):
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
function Clkd() {
var ppnl = document.getElementById("if1");
ppnl.src = "test.aspx";
$find('<%= MPE.ClientID %>').show();
}
function Clkd2() {
var ppnl = document.getElementById("if1");
ppnl.src = "";
$find('<%= MPE.ClientID %>').hide();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<cc1:ToolkitScriptManager runat="server" ID="scriptmanager1">
</cc1:ToolkitScriptManager>
<asp:Panel ID="pnl1" runat="server">
<iframe id="if1"></iframe>
<asp:Button ID="btnHidePopup" runat="server" Text="Hide" />
</asp:Panel>
<asp:Button ID="btnShowPopup" runat="server" Text="Show" OnClientClick="Clkd();" />
<cc1:ModalPopupExtender ID="MPE" runat="server" TargetControlID="btnShowPopup" PopupControlID="pnl1"
DropShadow="true" OkControlID="btnHidePopup" OnOkScript="Clkd2()" CancelControlID="btnHidePopup">
</cc1:ModalPopupExtender>
</form>
</body>
Test.aspx:
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
PageMethods.Testpm("Test", fnd);
});
function fnd(str) {
alert(str);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<cc1:ToolkitScriptManager runat="server" ID="scriptmanageriframe" EnablePageMethods="true">
</cc1:ToolkitScriptManager>
Hello World this is game.
</div>
</form>
</body>
Test.aspx.ce (Webmethod):
[System.Web.Services.WebMethod(EnableSession = true)]
public static string Testpm(String alrt)
{
return "Ok";
}
I hope it helps!
U can try with different popUp
for Example:
asp:ModalPopupExtender also available in ajaxtoolkit
jquery dialog popup.
I will prefer you to go with jquery dialog popup instead of ajaxpopup panel using the same web method in c# and jquery code you have written.
Use ClientIdMode="Static" on the MPE and use MPE id directly in $find().
ASPX Code:
<asp:ModalPopupExtender ID="modalpopup" ClientIDMode="Static" runat="server" CancelControlID="btnCancel"
OkControlID="btnOkay" TargetControlID="Button1" PopupControlID="Panel1"
Drag="true" >
</asp:ModalPopupExtender>
Javscript code:
$find('modalpopup').show(); // to show popup
$find('modalpopup').hide(); // to hide popup
IE9 has problem with pagemethods while having pagemethods in bothpage (mainpage,popuppanelpage).
you can use pagemethods in webservice(.asmx) file
i tried like below:
defaultpage.aspx
<head id="Head1" runat="server">
<title>Untitled Page</title>
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
function fnd123(str){
alert(str);
}
function objFailed1(data) {
fnd123(data);
}
function objGot1(data) {
fnd123(data.d);
}
function Clkd(){
var ppnl=document.getElementById("if1");
$.ajax({
url: "Testser.asmx/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
data:'{"FileName":"Data from default page"}',
type: 'POST',
success:objGot1,
error: objFailed1
});
ppnl.src="Test1.aspx";
$find('MPE').show();
}
function Clkd2(){
var ppnl=document.getElementById("if1");
ppnl.src="";
$find('MPE').hide();
//PageMethods.clearPageData("/Test1.aspx",fnd1);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager runat="server" ID="ToolkitScriptManager1" EnablePageMethods="true" EnablePartialRendering="false"/>
<div>
<input type="button" onclick="javascript:Clkd();return false;" value="Click" />
<div>
<asp:ModalPopupExtender ID="MPE" PopupControlID="popupPanel" PopupDragHandleControlID="popupPanel"
runat="server" Enabled="True" TargetControlID="btnOk" CancelControlID="BtnCancel"
BackgroundCssClass="PopupBackground" Drag="True" EnableViewState=true >
</asp:ModalPopupExtender>
<asp:Button Style="display: none" ID="BtnOk" runat="server"></asp:Button>
<asp:Button Style="display: none" ID="BtnCancel" runat="server"></asp:Button>
</div>
<div>
<asp:Panel ID="popupPanel" runat="server" Style="overflow: hidden; z-index: 100000;
display: none; background-color: White; filter: alpha(opacity=100); opacity: 1.0;
height: auto;">
<asp:Panel ID="pnlLoginHeader" runat="server" CssClass="" Style="display: none;">
<table width="100%">
<tr style="text-align: center">
<td style="width: 97%;">
<p class="popupTitle">
<asp:Label runat="server" ID="lblTitle" Text=""></asp:Label>
</p>
</td>
<td style="width: 3%;">
<p style="text-align: right;">
<span id="lblPopupClose" style="cursor: pointer; color: White">Close</span>
</p>
</td>
</tr>
</table>
</asp:Panel>
<iframe id="if1" src="" class="" style=""></iframe>
</asp:Panel>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Redirect" />
</div>
</div>
</form>
</body>
Test1.aspx
<head id="Head1" runat="server">
<title>Untitled Page</title>
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script language="javascript" type="text/javascript">
function fnd(str){
alert(str);
}
function objFailed1(data) {
fnd(data);
}
function objGot1(data) {
fnd(data.d);
}
function Clkdwebservice(){
$.ajax({
url: "Testser.asmx/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
data:'{"FileName":"Data from test page"}',
type: 'POST',
success:objGot1,
error: objFailed1
});
}
</script>
</head>
<body>
<form id="form1" runat="server" enableviewstate="false">
<asp:ToolkitScriptManager runat="server" ID="ToolkitScriptManager1" EnablePageMethods="true" />
<div>
<input type="button" onclick="javascript:Clkdwebservice();return false;" value="Click" />
<input type="button" onclick="javascript:parent.Clkd2();return false;" value="Close" />
</div>
</form>
</body>
Testser.asmx.cs
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
[ToolboxItem(false)]
public class Testser : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public String GetData(String FileName)
{
string msg = FileName;
return msg;
}
}
its working fine for me.please check it

Button in GridView in UpdatePanel Throws "Invalid postback or callback argument" on Click

I'm trying to make a jQuery confirm dialog call a web method. The dialog is called when the delete button in a GridView in an UpdatePanel is clicked.
However, when I click on the button, an error "Invalid postback or callback argument." I searched through some of the questions/answers here and tried overriding the Render event to register the UpdatePanel.
Here's my aspx page:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="DoPostBack._Default" %>
<asp:Content ID="conStyles" runat="server" ContentPlaceHolderID="cphStyles">
</asp:Content>
<asp:Content ID="conMain" runat="server" ContentPlaceHolderID="cphMain">
<asp:UpdatePanel ID="upMovies" runat="server" UpdateMode="Conditional" onload="upMovies_Load">
<ContentTemplate>
<asp:GridView ID="gvItems" runat="server" CssClass="tbl-movies" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Title" HeaderText="Title" HeaderStyle-CssClass="col-title-header" ItemStyle-CssClass="col-title"/>
<asp:BoundField DataField="Director" HeaderText="Director" HeaderStyle-CssClass="col-director-header" ItemStyle-CssClass="col-director" />
<asp:BoundField DataField="Year" HeaderText="Year" HeaderStyle-CssClass="col-year-header" ItemStyle-CssClass="col-year" />
<asp:TemplateField ItemStyle-HorizontalAlign="Left" ItemStyle-CssClass="table-actions">
<ItemTemplate>
<asp:ImageButton ID="btnEdit" ImageUrl="Images/edit.png" runat="server"
Text="Edit" UseSubmitBehavior="False" />
<asp:ImageButton ID="btnDelete" ImageUrl="Images/delete.png" runat="server"
Text="Delete" UseSubmitBehavior="False" CssClass="btn-delete-movie" />
<asp:HiddenField ID="hfMovieId" runat="server" Value='<%# Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<div id="confirmDelete" class="popup popup-confirm">
<div class="popup-title">
<h4>Delete Movie</h4>
</div>
<div class="popup-content">
<div class="confirm-message">
</div>
<div class="buttons center">
<input id="btnDeleteConfirm" type="button" value="OK" class="button btn-confirm" />
<input id="btnDeleteCancel" type="button" value="Cancel" class="button btn-delete-cancel btn-close-popup" />
</div>
</div>
</div>
</asp:Content>
<asp:Content ID="conScripts" runat="server" ContentPlaceHolderID="cphScripts">
<script src="Scripts/site.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var btnDelete = $('.btn-delete-movie');
btnDelete.on('click', function (e) {
e.preventDefault();
var row = $(this).closest('tr'),
title = row.find('.col-title').text(),
movieId = parseInt(row.find('input[type=hidden]').val());
showConfirmPopUp('confirmDelete',
'Are you sure you want to delete the movie "' + title + '"?',
function () { deleteMovie(movieId); }, //call the DeleteMovie web method
function () { }); //do nothing else
});
});
function deleteMovie(id) {
$.ajax({
type: 'POST',
contentType: 'application/json',
data: '{"id":' + id + '}',
url: 'Default.aspx/DeleteMovie',
dataType: 'json',
success: function (data) {
__doPostBack('<%= upMovies.ClientID %>', '');
closePopUp('confirmDelete');
},
error: function (jqXHR, textStatus, errorThrown) {
showError(jqXHR, textStatus, errorThrown);
}
});
}
</script>
</asp:Content>
Code-behind:
public partial class _Default : System.Web.UI.Page
{
#region Events
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateMovies();
}
}
protected override void Render(HtmlTextWriter writer)
{
ClientScript.RegisterForEventValidation(upMovies.UniqueID);
foreach (GridViewRow row in gvItems.Rows)
{
var btnDelete = row.FindControl("btnDelete");
var btnEdit = row.FindControl("btnEdit");
ClientScript.RegisterForEventValidation(btnDelete.UniqueID);
ClientScript.RegisterForEventValidation(btnEdit.UniqueID);
}
base.Render(writer);
}
protected void upMovies_Load(object sender, EventArgs e)
{
PopulateMovies();
}
#endregion
#region Private Methods
private void PopulateMovies()
{
var data = from m in Movie.GetAll()
orderby m.Year descending, m.Title ascending
select m;
gvItems.DataSource = data;
gvItems.DataBind();
}
#endregion
#region Web Methods
[WebMethod]
public static object DeleteMovie(int id)
{
Movie.Delete(id);
return UpdateItems();
}
#endregion
}
I'm using the jQuery approach because I don't want to use the ModalPopupExtender. I don't want to set EnableEventValidation to false either.
Also, why is the upMovies_Load called when I click on the delete button? Shouldn't it only be called when the ok button of the confirm dialog is clicked?
I'm kind of a beginner, help would be greatly appreciated.
Thank you :)
Okay, you have to rebind the JavaScript again via
Sys.WebForms.PageRequestManager.GetInstance().add_endRequest(function(){
//$(document).ready() code here
});

InvalidCastExceptions when setting GridViewRow attributes

I'm working on a context menu for items in my GridView, but there's one major snag. I can't seem to figure out how to send the PK value for the row that is right-clicked on to the JQuery that interacts with my HTTP Handler to update the database.
Basically, the context menu will have 3 items, Reply, Mark as Read, and Delete.
In each case I need the mailid value from the database to be available to the JQuery so that I can redirec the user to a page where they can reply to the selected mail or to tell the HTTP Handler which item in the database it's supposed to update.
Here's my code:
protected void gvItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onClick"] = "getMailDetail(" + DataBinder.Eval(e.Row.DataItem, "mailid") + ")";
e.Row.Attributes["id"] = DataBinder.Eval(e.Row.DataItem, "mailid");
Label lblStatus = (Label)e.Row.FindControl("lblStatus");
if (lblStatus.Text == "unread")
{
e.Row.Font.Bold = true;
}
}
}
I'm setting the onClick attribute for the Rows so that clicking anywhere on the GridViewRow will trigger the page to display the mail in detail. I figured I could get the mailid value in the same way using a different attribute.
And on the .aspx...
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.contextMenu.js"></script>
<script type="text/javascript">
function getMailDetail(mailId) {
$.ajax({
type: "GET",
url: '<%= ResolveUrl("~/GetMail.ashx") %>',
data: { mid: mailId },
success: function (data) {
var pnlList = $('#<%= pnlList.ClientID %>');
var pnlMail = $('#<%= pnlMail.ClientID %>');
var lblFrom = $('#<%= lblFrom.ClientID %>');
var lblDate = $('#<%= lblDate.ClientID %>');
var lblSubject = $('#<%= lblSubject.ClientID %>');
var lblMessage = $('#<%= lblMessage.ClientID %>');
lblFrom.text(data.From);
lblDate.text(data.Date);
lblSubject.text(data.Subject);
lblMessage.text(data.Message);
pnlList.css("display", "none");
pnlMail.css("display", "block");
}
});
}
function markRead(mailId) {
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/MailAction.ashx") %>',
data: { mid: mailId, act: "markRead" },
success: window.location = "Inbox.aspx"
});
}
function deleteMail(mailId) {
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/MailAction.ashx") %>',
data: { mid: mailId, act: "Delete" },
success: window.location = "Inbox.aspx"
});
}
</script>
<div class="columns">
<div class="leftcol">
Compose Message
<ul>
<li>Sent Items</li>
<li class="active">Inbox</li>
<li>Deleted Items</li>
</ul>
</div>
<div class="rightcol">
<asp:Panel runat="server" ID="pnlList">
<div class="rightalign">
<asp:Label runat="server" ID="lblCount"></asp:Label>
</div>
<asp:GridView runat="server" ID="gvItems" DataKeyNames="mailid"
AutoGenerateColumns="false" onrowdatabound="gvItems_RowDataBound"
Width="100%">
<Columns>
<asp:TemplateField ItemStyle-CssClass="centeralign">
<HeaderTemplate>
<asp:CheckBox runat="server" ID="chkSelectAll" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkSelect" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-CssClass="hidden" HeaderStyle-CssClass="hidden">
<ItemTemplate>
<asp:Label runat="server" ID="lblStatus" Text='<%# DataBinder.Eval(Container.DataItem, "status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-CssClass="hidden" HeaderStyle-CssClass="hidden" DataField="mailid" />
<asp:BoundField DataField="firstname" HeaderText="From" SortExpression="firstname" />
<asp:BoundField DataField="datesent" HeaderText="Date" SortExpression="datesent" DataFormatString="{0:yyyy/MM/dd HH:mm}" />
<asp:BoundField DataField="subject" HeaderText="Subject" SortExpression="subject" />
</Columns>
</asp:GridView>
</asp:Panel>
<asp:Panel runat="server" ID="pnlMail" cssclass="hidden">
<p>From: <asp:Label runat="server" ID="lblFrom"></asp:Label><br />
Sent On: <asp:Label runat="server" ID="lblDate"></asp:Label><br />
Subject: <asp:Label runat="server" ID="lblSubject"></asp:Label></p>
<p><asp:Label runat="server" ID="lblMessage"></asp:Label></p>
</asp:Panel>
</div>
</div>
<!-- Row Context Menu -->
<ul id="contextmenu" class="contextMenu">
<li>Reply</li>
<li>Mark As Read</li>
<li>Delete</li>
</ul>
<script type="text/javascript">
$(document.ready(function() {
$(".dataRow").contextMenu({
menu: 'contextmenu' },
function(action, el, pos, mid) {
contextMenuWork(action, el, pos);
}
);
},
function contextMenuWork(action, el, pos) {
var mid = $(el).attr("id");
switch (action) {
case "reply":
{
window.location = "Reply.aspx?id=" + mid;
break;
}
case "mread":
{
markRead(mid);
break;
}
case "delete":
{
deleteMail(mid);
break;
}
}
}
);
</script>
Unfortunately there seems to be a problem in my approach here as I'm getting an InvalidCastException on the assignment of the id attribute on the newly bound GridViewRow:
Cannot implicitely convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)
So, I replace that line with this
e.Row.Attributes["id"] = (string)DataBinder.Eval(e.Row.DataItem, "mailid");
And now, although there are no errors that Visual Studio can tell me about at design time, at runtime, I get the following InvalidCastException:
Unable to cast object of type 'System.Int32' to type 'System.String'.
I have no idea where the integer is coming from here so I don't know how to proceed.
Any help will be greatly appreciated.
I never seemed able to get a working cast on the value here, so what I did was to change the RowDataBound void to the following:
protected void gvItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var mailid = DataBinder.Eval(e.Row.DataItem, "mailid");
e.Row.Attributes["onClick"] = "getMailDetail(" + DataBinder.Eval(e.Row.DataItem, "mailid") + ")";
e.Row.Attributes["id"] = mailid.ToString();
Label lblStatus = (Label)e.Row.FindControl("lblStatus");
if (lblStatus.Text == "unread")
{
e.Row.Font.Bold = true;
}
}
}
Declaring a new var and with the DataItem value for "mailid" and then giving it a .ToString() fixed all my problems

Is it possible to reference a linkbotton outside an update panel as the update trigger?

THIS IS THE SITE.MASTER ASPX PAGE
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="Prototype4.SiteMaster" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
alert("JS code in general: OK");
$(function () {
$("#lnkShowOtherPage").click(function () {
alert("OtherPagePanel length: " + $("#OtherPagePanel").length);
alert("OtherPagePanel load: " + $("#OtherPagePanel").load);
$("#OtherPagePanel").load("/EntryForms/OpenCase.aspx");
});
});
function updateClock() {
var currentTime = new Date();
var currentHours = currentTime.getHours();
var currentMinutes = currentTime.getMinutes();
var currentSeconds = currentTime.getSeconds();
// Pad the minutes and seconds with leading zeros, if required
currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;
currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds;
// Choose either "AM" or "PM" as appropriate
var timeOfDay = (currentHours < 12) ? "AM" : "PM";
// Convert the hours component to 12-hour format if needed
currentHours = (currentHours > 12) ? currentHours - 12 : currentHours;
// Convert an hours component of "0" to "12"
currentHours = (currentHours == 0) ? 12 : currentHours;
// Compose the string for display
var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
// Update the time display
document.getElementById("clock").firstChild.nodeValue = currentTimeString;
}
Case Management System
Welcome
!
[ ]
<%--Welcome:
!--%>
Welcome: Guest
[ Log In ]
</asp:LoginView>
<%-- [ <asp:LoginStatus ID="MasterLoginStatus" runat="server" LogoutAction="Redirect" LogoutPageUrl="~/Logout.aspx" /> ] --%>
</div>
<div class="topNav">
<asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal">
<Items>
<asp:MenuItem NavigateUrl="~/Default.aspx" Text="Home"
ImageUrl="~/homeIcon.png"/>
<asp:MenuItem NavigateUrl="~/About.aspx" Text="About"
ImageUrl="~/aboutIcon.png"/>
<asp:MenuItem ImageUrl="~/contact_us_icon1.png" NavigateUrl="~/Contact.aspx"
Text="Contact Us" Value="Contact Us"></asp:MenuItem>
</Items>
</asp:Menu>
</div>
</div>
</div>
</div>
<div class="page" style="margin-top:5px;height:auto;">
<div class="right" style="border-style:solid;padding-left: 4px; padding-right:4px;">
<asp:Button ID="newsButton" runat="server" Text="News"
class="fnctButton" Height="25px" Width="70px" />
<div style="border-color: White; border-width:medium; border: medium;">
<p style="text-align:left; font-size:1.2em; color:White;">
This is a place holder for some real text that is displayed regarding news within the departement and additional links to external sites for news.
</p>
</div>
<asp:ContentPlaceHolder ID="RightNewsItem" runat="server"/>
</div>
<div class="left" style="border-style:solid;">
<asp:Button ID="functionButton" runat="server" Text="System Functions"
class="fnctButton" Height="25px" Width="170px" />
<asp:ContentPlaceHolder ID="LeftNavigation" runat="server">
</asp:ContentPlaceHolder>
</div>
<div class="middle" style= "border-bottom-style:solid;">
<asp:ContentPlaceHolder ID="MainContent" runat="server"/>
</div>
</div>
<div class="clear">
</div>
<div class="footer">
<span style="font-size: small;color: #FFFFFF;"><strong>Copyright 2011 JustRite Software Inc.</strong></span></div>
</form>
AND THIS ONE IS THE CASE ADMIN PAGE BASED ON THE MASTER PAGE. THERE ARE TWO BUTTONS ON THE LEFT NAVIGATION PANE THAT SHOULD LOAD A THIRD PAGE (OPENCASE OR ADDEXHIBIT) IN THE CENTRE SPACE DEPENDING ON WHICH BUTTON IS CLICKED. THE CASE ADMIN PAGE .ASPX BELOW.
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="CaseAdmin.aspx.cs" Inherits="Prototype4.CaseAdmin" %>
<%#PreviousPageType VirtualPath="~/Account/Login.aspx"%>
<div style="margin-top:20px; margin-bottom:20px;">
<p class="actionButton">
<a id="lnkShowOtherPage" href="#">Open Case</a>
</p>
<p class="actionButton"><asp:LinkButton ID="RegisterExhibitLinkButton"
runat="server" onclick="RegisterExhibitLinkButton_Click">Register Exhibit</asp:LinkButton> </p>
</div>
<div id="OtherPagePanel" style="width:auto">
</div>
THIS SECTION REPRESENTS THE CODE BEHIND FOR THE CASEADMIN PAGE THUS THE .CS CODES
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Prototype4
{
public partial class CaseAdmin : System.Web.UI.Page
{
//string userid;
//string strUsername;
protected void Page_Load(object sender, EventArgs e)
{
//strUsername = Session["Username"].ToString();
}
//public String AdminUserID
//{
// get
// {
// //return userid;
// }
//}
//userid = PreviousPage.AdminID;
//Response.Redirect("~/EntryForms/OpenCase.aspx", false);
/* if (PreviousPage != null)
{
TextBox SourceTextBox =
(TextBox)PreviousPage.FindControl("UserName");
if (SourceTextBox != null)
{
userid = SourceTextBox.ToString();
}
}*/
protected void RegisterExhibitLinkButton_Click(object sender, EventArgs e)
{
Response.Redirect("~/EntryForms/AddExhibit.aspx", false);
}
}
}
THIS IS ONE OF THE TWO PAGES THAT SHOULD LOAD DEPENDING ON THE BUTTON CLICK. I HAVE ATTACHED THE CODE FOR THE OPENCASE FORM SO THAT WOULD CORRESPOND WITH THE OPENCASE LINK BUTTON ON THE LEFT. OPENCASE.ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="OpenCase.aspx.cs" Inherits="Prototype4.EntryForms.OpenCase" %>
<%#PreviousPageType VirtualPath="~/CaseAdmin.aspx" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>
.casePage
{
width: 430px;
height:314px;
background-color:#3a4f63;
}
.style1
{
font-weight: normal;
color: #FFFFFF;
text-align: center;
}
.style2
{
font-weight: normal;
color: Black;
text-align: left;
margin-left: 20px;
margin-top:0px;
}
.style3
{
width: 85%;
}
.style4
{
width: 175px;
background-color: #808080;
}
.style5
{
background-color: #CCCCCC;
padding-left:10px;
}
</style>
Open Case
Form
<table class="style3" align="center">
<tr>
<td class="style4">
<p class="style2">
Case ID:
</p>
</td>
<td class="style5">
<asp:TextBox ID="caseIDTextBox"
runat="server" height="22px" width="154px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style4">
<p class="style2">
Case Description:
</p>
</td>
<td class="style5">
<asp:TextBox ID="caseDescTextBox"
runat="server" height="22px" width="154px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style4">
<p class="style2">
Case Administrator ID:
</p>
</td>
<td class="style5">
<asp:TextBox
ID="caseAdminIDTextBox" runat="server" height="22px" width="154px"></asp:TextBox>
</td>
</tr>
</table>
</div>
<div>
<table class="style3" align="center">
<tr>
<td align="left">
<asp:Button ID="openCaseBotton" runat="server" Text="Open Case"
onclick="openCaseBotton_Click" />
</td>
<td align="center">
<asp:Button ID="addExhibitBotton" runat="server" Text="Add Exhibit"
onclick="addExhibitBotton_Click" />
</td>
<td align="right">
<asp:Button ID="cancelButton" runat="server" Text="Cancel"
onclick="cancelButton_Click" /></td>
</tr>
</table>
</div>
</div>
</form>
AND LASTLY THE OPENCASE.CS PAGE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
namespace Prototype4.EntryForms
{
public partial class OpenCase : System.Web.UI.Page
{
string adminString;
protected void Page_Load(object sender, EventArgs e)
{
adminString = "CA123";
}
protected void openCaseBotton_Click(object sender, EventArgs e)
{
//SQL connection string
SqlDataSource CSMDataSource = new SqlDataSource();
CSMDataSource.ConnectionString = ConfigurationManager.ConnectionStrings["CMSSQL3ConnectionString"].ToString();
//SQL Insert command with variables
CSMDataSource.InsertCommandType = SqlDataSourceCommandType.Text;
CSMDataSource.InsertCommand = "INSERT INTO Filing (FilingID, FilingDesc, DateOpened, FilingPriority, AdministratorID) VALUES (#FilingID, #FilingDesc, #DateOpened, #FilingPriority, #AdministratorID)";
//Actual Insertion with values from textboxes into databse fields
CSMDataSource.InsertParameters.Add("FilingID", caseIDTextBox.Text);
CSMDataSource.InsertParameters.Add("FilingDesc", caseDescTextBox.Text);
CSMDataSource.InsertParameters.Add("DateOpened", DateTime.Now.ToString());
CSMDataSource.InsertParameters.Add("FilingPriority", null);
CSMDataSource.InsertParameters.Add("AdministratorID", adminString.ToString());
int rowsCommitted = 0;
//Try catch method to catch exceptions during insert
try
{
rowsCommitted = CSMDataSource.Insert();
}
catch (Exception ex)
{
//error message displayed when exception occurs
string script = "<script>alert('" + ex.Message + "');</script>";
Response.Write("The following Error occurred while entering the records into the database" + " " + ex.ToString() + " ");
Response.Redirect("~/ErrorPage.aspx", false);
}
finally
{
CSMDataSource = null;
}
//Where to go next if insert was successful or failed
if (rowsCommitted != 0)
{
Response.Redirect("~/CaseAdmin.aspx", false);
}
else
{
Response.Redirect("~/ErrorPage.aspx", false);
}
}
protected void addExhibitBotton_Click(object sender, EventArgs e)
{
Response.Redirect("~/EntryForms/AddExhibit.aspx", false);
}
protected void cancelButton_Click(object sender, EventArgs e)
{
Response.Redirect("~/CaseAdmin.aspx", false);
}
}
}
ALL I WANT TO DO IS GET THE RESPECTIVE PAGES TO LOAD INSIDE THE MAIN CONTENT AREA (THE MIDDLE SECTION) WITHOUT RELOADING THE PAGE. ITS BEEN A LONG WAY COMING BUT PROVED SUCCESSFUL WITH A LOT TO LEARN BUT I JUST WANT TO KNOW HOW I CAN APPLY THIS SAME TECHNIQUE TO THE OTHER BUTTON CLICK(ADD EXHIBIT) SINCE IN THE AJAX CODE IN THE HEADER OF THE MASTER PAGE SPECIFIES THE URL ON JUST ONE PAGE. HOW DO I DO THAT FOR SUBSEQUENT PAGES THAT USE THE MASTER PAGE AND WOULD BE DOING SIMILAR ACTIONS. FOR EXAMPLE THE CASE MANAGER PAGE THAT LOOKS LIKE THIS.
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="CaseManager.aspx.cs" Inherits="Prototype4.CaseManager" %>
This is a place holder for allerts about cases to which the investigator has been assigned to.
<div style="margin-top:20px; margin-bottom:20px;">
<p class="actionButton"><asp:LinkButton ID="AllocateOfficerLinkButton" runat="server">Allocate Officer</asp:LinkButton> </p>
<p class="actionButton"><asp:LinkButton ID="ReallocateLinkButton" runat="server">Reallocate Officer</asp:LinkButton> </p>
<p class="actionButton"><asp:LinkButton ID="SetPriorityLinkButton" runat="server">Prioritize Case</asp:LinkButton> </p>
<p class="actionButton"><asp:LinkButton ID="OpenCaseLinkButton" runat="server">Open Case</asp:LinkButton> </p>
<p class="actionButton"><asp:LinkButton ID="RegisterExhibitLinkButton" runat="server">Register Exhibit</asp:LinkButton> </p>
</div>
I WANT TO TO DO SOMETHING SIMILAR LIKE IN THE CASE ADMIN PAGE BUT AM WONDERING WHAT THE CODES WILL ADD UP TO BE LIKE IN THE MASTER PAGE.
THANKS...
I actually just wanted to load a form
that is created in another asp. page
into the main content area...
I fear that what you need is not UpdatePanel but rather "ordinary" AJAX loading that other page contents into some element.. using jQuery it's as simple as:
$("#OtherPagePanel").load("OtherPage.aspx");
Where OtherPagePanel is the ID of some element in your .aspx code.
You can pass parameters to the other page over the URL, if you need to Post data it's still possible but requires some extra lines - let us know in such case.
Edit:
In the placeholder where you want the data from other page to appear, have this:
<div id="OtherPagePanel"></div>
Have such link in the other placeholder: (no need in LinkButton, ordinary HTML link is enough)
<a id="lnkShowOtherPage" href="#">Show other page</a>
Now in the <head> section of your master page add this code and it's all done:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#lnkShowOtherPage").click(function() {
$("#OtherPagePanel").load("OtherPage.aspx");
});
});
</script>
You can also copy the jQuery.min.js file to your own server and change the src accordingly.
Edit 2:
In order to debug add such lines to the code, it will tell what went wrong:
<script type="text/javascript">
alert("JS code in general: OK");
$(function() {
alert("Page load: OK");
$("#lnkShowOtherPage").click(function() {
alert("Link click: OK");
$("#OtherPagePanel").load("OtherPage.aspx");
});
});
</script>
Reload the page and let us know what alerts you get.
Edit 3:
Based on the previous debug results, have this code now:
<script type="text/javascript">
$(function() {
$("#lnkShowOtherPage").click(function() {
alert("OtherPagePanel length: " + $("#OtherPagePanel").length);
alert("OtherPagePanel load: " + $("#OtherPagePanel").load);
$("#OtherPagePanel").load("OtherPage.aspx");
});
});
</script>
Edit 4 and hopefully last:
In order to load different page into different div by clicking different button in addition to everything you already have, have such code:
<script type="text/javascript">
$(function() {
$("#lnkShowOtherPage").click(function() {
$("#OtherPagePanel").load("OtherPage.aspx");
});
$("#lnkShowDifferentOtherPage").click(function() {
$("#DifferentOtherPagePanel").load("DifferentOtherPage.aspx");
});
});
</script>
Is it a postback trigger or an async postback trigger?
i think you can register controls as post back or async on a script manager level with:
Control oControl;
ScriptManager1.RegisterAsyncPostBackControl(oControl);
you could try that

Categories

Resources