Display SqlDataSource data in HTML table (DataTables Plugin) - asp.net

I want to display SQL Server data in a table <td> so I can use the plugin at https://datatables.net/ I am able to bind the data to things such as
<asp:PlaceHolder ID = "PlaceHolder1" runat="server" />
such as in this tutorial: https://www.aspsnippets.com/Articles/Display-data-from-database-in-HTML-table-in-ASPNet.aspx
However, the plugin needs a class and id from a table, and therefore doesn't work. I tried inserting class and id that the plugin needs like this but did not work
// Table start.
html.Append("<table border = '1'>");
html.Append("<table class = "display" id = "example">");
Is there a way of inserting a class and id to the table through html.append?
Thanks

If you have a GridView, you need to use the ClientID. Place the below GridView and JavaScript on the same aspx page.
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"/>
<asp:GridView ID="GridView1" runat="server"
OnRowDataBound="GridView1_RowDataBound">
</asp:GridView>
<script type="text/javascript">
$(document).ready(function () {
$('#<%= GridView1.ClientID %>').DataTable();
});
</script>
However, for a GridView to work with DataTables, you need to add a OnRowDataBound event. Then in code behind add the following code.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.TableSection = TableRowSection.TableHeader;
}
}
This add the <thead> and <tbody> tags to the generated html, which is needed by datatables.net.

I found this that also explained that i needed <thread> tags which i was missing.
Apply Jquery DataTables plugin to ASP GridView

Related

Show a div in asp.net on condition

Is it Possible to show/notshow a div in asp.net depending if cookies are set or not?
Note: the div is an html form invoked with javascript in asp.net.
Here the code in asp.net
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" runat="Server">
<script type="text/javascript">
$(document).ready(function () { $('#'<%= webform.ClientID %>).load('popup.html');
</script><div id="webform" runat="Server">
</div>
</asp:Content>
And in code behind:
protected void Page_Load(object sender, EventArgs e)
{ webform.Visible= true;}
Note that the webform is visible when the code is: (nothing is code behind)
<script type="text/javascript">
$(document).ready(function () { $('#webform').load('popup.html'); })
</script>
<div id="webform" >
</div>
</asp:Content>
The goal is to make this visible or not depending if cookie has been set or not.
I already tested that the form (in HTML) is setting the cookies(with javascript through webform)
Here's the logic for you to try
Make your DIV a server control by adding runat="server" property
Also have an ID property for your DIV tag
set this DIV's visibility from your code behind based on the Cookie values
E.g.
Markup code
<div id="MyDiv" runat="server"></div>
Code behind
MyDiv.Visible = true; // set this based on the cookie value
UPDATE 1
This is how you'd use your DIV in Scripts
<script type="text/javascript">
$(document).ready(function () { $('#'<%= MyDiv.ClientID %>).load('popup.html'); })
</script>
UPDATE 2
I made a mistake in my UPDATE 1. You should write the JQuery selector like '#<%= MyDiv.ClientID %>' and not like '#'<%= MyDiv.ClientID %> (Note the ' marks).
And, you also made a mistake in your script. You've missed a }) at the end of the script.
Anyway, here's the working solution. (I tried it so don't tell it's not working :-))
<script type="text/javascript">
$(document).ready(function () { $('#<%= webform.ClientID %>').load('popup.html');} )
</script>
<div id="webform" runat="Server"></div>
Hope you could understand this.

iframe error when runat="server"

I have a iframe in one of my web pages with runat="server" and a javascript function assigned to the onload event. When the page renders it gives an error as
"CS1012: Too many characters in character literal"
When I remove the runat="server" attribute it works perfectly but I need the iframe to runat="server". How can I fix this?
<iframe id='contentFrame' name='contentFrame'
runat="server" width="500"
onload="resizeFrame(document.getElementById('contentFrame'))">
</iframe>
When you use runat="server" - 'onload' starts being parsed as C# Event of Html Server Control, like Button.Click. You should set a name of C# event handler method in the class of your control/page (NOT JAVASCRIPT). This code will work:
<script runat="server">
void contentFrame_onLoadServer(object sender, EventArgs e)
{
if (!IsPostBack)
contentFrame.Attributes.Add("onLoad", "contentFrame_onLoadClient();");
}
</script>
<script type="text/javascript">
function contentFrame_onLoadClient() {
resizeFrame(document.getElementById('<%=contentFrame.ClientID %>'));
}
function resizeFrame(element) {
alert(element); // do your logic here
}
</script>
<iframe
runat="server"
id='contentFrame'
name='contentFrame'
width="500"
onload="contentFrame_onLoadServer"
/>
You cannot "just" add the onload for client side code, because it's "occupied" by the .NET server side onload. You need to hook it up by code (and I enhanced #Philipp 's code):
<script runat="server">
void onIframeLoad(object sender, EventArgs e)
{
if (!IsPostBack)
{
contentFrame.Attributes.Add("onload", "resizeFrame(document.getElementById('contentFrame'));");
}
}
</script>
<iframe id='contentFrame'
name='contentFrame'
runat="server" width="500"
onload="onIframeLoad"/>
replace single quotation with double:
< iframe id="contentFrame" name="contentFrame" runat="server" width="500" onload="resizeFrame(document.getElementById('contentFrame'))">
You can not write document.getElementById('contentFrame') in onload method. Write it in your javascript function instead.
runat="server" changes the ID of the IFrame.
instead of passing "document.getElementById('contentFrame')" pass "this" in javascript.
Or you may also pass
document.getElementById('<%= contentFrame.ClientID%>')

How to submit aspx page value to Tridion RTF

I am creating Tridion GUI Extension, in this i have created a button ("InsertCP") in the Ribbon toolbar.
The scenario is:
1.User selects any text from the Rich Text Box of the component
2.User clicks the "InsertCP" button from the ribbon toolbar.
3.when the user clicks the button , i am opening my custom aspx page.
4.From the custom aspx page, user can select "Component" and "Component Template".
5.I am storing the selected component and component template tcm id in a variable.
6.I have submit button in the custom aspx page.
7.when the user clicks the submit button, i need to format the selected text as below in the Rich Text box source.
Ex:
Selected Text
I have done upto the step 6, i am tryng the step 7, when i click the submit button am not able to submit the selected ID.
My ASPX page:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:c="http://www.sdltridion.com/web/ui/controls">
<head runat="server">
<title></title>
<cc:tridionmanager runat="server" editor="ExampleEditor" isstandaloneview="true">
<dependencies runat="server">
<dependency runat="server">Tridion.Web.UI.Editors.CME</dependency>
<dependency runat="server">Tridion.Web.UI.Editors.CME.Controls</dependency>
</dependencies>
</cc:tridionmanager>
</head>
<div>
<asp:TextBox ID="txttags" runat="server" Width="800px" ></asp:TextBox>
<asp:Button ID="btnsubmit" runat="server" Text="Submit" onclick="btnsubmit_Click" />
<c:button id="InsertButton" runat="server" class="customButton greybutton" label="Insert" />
</div>
Cs code :
protected void btnsubmit_Click(object sender, EventArgs e)
{
txttags.Text = "anyvalue.";
}
and java script are same as exiting one..
But i am getting error on runtime.Do i need to add any namespace in cs page.
My CS page will have so many events like below.Cant i use tridion control button for this page.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tridion.ContentManager.CoreService.Client;
using System.Xml.Linq;
using System.Xml;
namespace Somename
{
public partial class Classname
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ddSelectOption_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void lbPublication_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void lbPubFolders_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void lbComponent_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void lbComponentTemplate_SelectedIndexChanged(object sender, EventArgs e)
{
}
I'll provide a second answer to your updated question, although you are still keeping us a bit in the dark since you only mention you get a runtime error and not what that exactly is (it is impossible for me to provide a good answer if I don't know what error you get).
Your ASPX page should look something like this:
<%# Page Language="C#" AutoEventWireup="true" Inherits="Example.MyPopup" ClassName="MyPopup" %>
<%# Import Namespace="Tridion.Web.UI" %>
<%# Register TagPrefix="ui" Namespace="Tridion.Web.UI.Editors.CME.Controls" Assembly="Tridion.Web.UI.Editors.CME" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html id="MyPopup" class="tridion popup" xmlns:c="http://www.sdltridion.com/web/ui/controls" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My Popup Example</title>
<cc:TridionManager runat="server" Editor="ExampleEditor" IsStandAloneView="false">
<dependencies runat="server">
<dependency runat="server">Tridion.Web.UI.Editors.CME</dependency>
<dependency runat="server">Tridion.Web.UI.Editors.CME.Controls</dependency>
</dependencies>
</cc:TridionManager>
</head>
<body>
<table id="tblHeight" border="0" cellpadding="0" cellspacing="0">
<tr>
<td id="InputField" valign="top">
<table>
<tr>
<td id="NameLabelCell" nowrap="nowrap">My Label</td>
<td><input id="txttags" name="txttags" value="" tabindex="1" /></td>
</tr>
</table>
</td>
</tr>
<tr id="FooterRow">
<td class="footer" align="right">
<div class="BtnWrapper">
<c:Button ID="BtnOk" runat="server" TabIndex="2" Label="<%$ Resources: Tridion.Web.UI.Strings, OK %>" />
<c:Button ID="BtnCancel" runat="server" TabIndex="3" Label="<%$ Resources: Tridion.Web.UI.Strings, Cancel %>" />
</div>
</td>
</tr>
</table>
</body>
</html>
Note: the table markup is copied directly from the Anchor popup, feel free to use divs instead and style them any way you want, the example is meant to show you how to reuse the existing Tridion controls
Your CS would then become:
using Tridion.Web.UI.Core;
using Tridion.Web.UI.Controls;
using Tridion.Web.UI.Core.Controls;
using Tridion.Web.UI.Editors.CME.Views.Popups;
namespace Example
{
[ControlResources("Example.MyPopup")]
public class MyPopup : PopupView
{
}
}
It doesn't contain anything, and it doesn't need to, as all the actions you will be doing in your JavaScript as explained before.
Looking at your update I gather what you want is to create an anchor element based on the information from your ASPX page into the selected text of the Rich Text field of the Component.
To build something like that you can best look at something similar which is available. Simplest example I can think of is the Hyperlink button in the Format ribbon toolbar. That consists of two items:
..\Tridion\WebUI\Editors\CME\Views\Popups\Link\Link.aspx
..\Tridion\WebUI\Editors\CME\Views\Popups\Link\Link.js
The magic all happens inside the JavaScript file (as usually is done in these UI extensions). In the initialize() method, the selected part is extracted like so:
var p = this.properties;
var c = p.controls;
// Get selected acronym
p.OldLink = (window.dialogArguments && window.dialogArguments.link) ? window.dialogArguments.link : {};
The post back to the Rich text field is done in the _onOkButtonClicked(event) method like so:
this._buildNewLinkHtml();
this.fireEvent("submit", { link: this.properties.NewLink });
window.close();
You can take a closer look at the rest of the code in the Link.js file and rebuild it to suit your needs.
By the way, looking at the info you want to post back in the href, I would say its easier if you format it a bit more according to some sort of standard, you could for instance place your URIs there like JSON:
text
Or possibly even abuse the title attribute for your Component Template URI:
text
Since I'm assuming your Component Template code will use these values to do something special with this hyperlink construct.
Edit
The unrecognized tag prefix c error you show in the added image, you can solve by adding the correct namespace reference as I indicated in my answer here. So just add it in your HTML element:
<html xmlns:c="http://www.sdltridion.com/web/ui/controls" xmlns="http://www.w3.org/1999/xhtml">
As for the unrecognized cc tag prefix, you shouldn't need to bother with that one, it seems to be resolved at runtime just fine since you are running this inside the Tridion context.

How do I read the SelectedValue of a DropDownList in code behind, when the option has been added using JavaScript?

How do I read the SelectedValue of a DropDownList in code behind, when the option has been added using JavaScript?
A little more background: I have cascading drop down lists, and I would like to fill in the values using JavaScript, so that I avoid postbacks when the user changes the selection in the first drop down list.
I am not allowed to use an Update Panel.
I have build a simple demo demonstrating problem. Here is my markup code:
<p>
<asp:DropDownList runat="server" ID="FilterDropDownList" />
</p>
<p>
<asp:Button runat="server" ID="SearchButton" Text="Search"
onclick="SearchButton_Click" /><br/>
<asp:TextBox runat="server" ID="QueryTextBox" />
</p>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var filterDropDownListId = '#<%= FilterDropDownList.ClientID %>';
$(filterDropDownListId).append($('<option>').prop('value', 'Alpha').html('A'));
$(filterDropDownListId).append($('<option>').prop('value', 'Beta').html('B'));
});
</script>
And in the code behind I have the following:
protected override void Render(HtmlTextWriter writer)
{
// Register the allowed values for the down down list.
Page.ClientScript.RegisterForEventValidation(FilterDropDownList.UniqueID, "Alpha");
Page.ClientScript.RegisterForEventValidation(FilterDropDownList.UniqueID, "Beta");
base.Render(writer);
}
protected void SearchButton_Click(object sender, EventArgs e)
{
Response.Redirect(
String.Format("{0}?dropdown={1}&query={2}",
Request.Url.AbsolutePath,
FilterDropDownList.SelectedValue,
QueryTextBox.Text));
}
The problem is, that FilterDropDownList.SelectedValue is empty. I would have expected it to be either "Alpha" or "Beta". I can read the value of QueryTextBox.Text without problems.
It is possible to read MyDropDownList.SelectedValue when the values have been populated using JavaScript? Or do a have to use a different approach?
You can always write the selected value to a hidden textbox with javascript and read the value in the code-behind.

Working with Gridviews and File Transfers

I need to generate a Excel sheet during RunTime on a ItemCommand_click event in a GridView and transfer the file and then re-bind the GridView with the status change.
As we redirect the response with File transfer , How could I update the GridView?
I was looking to do something very similar on selected index change on the rows to output a reporting services report as a PDF. I was only able to get this to work with a response.redirect to another page that handled the output of the file. It looks like your issue really becomes the rebinding the grid after the status change, if you do a response.redirect, you can't touch your grid...
Take a look at this code. I found it on encosia.com. It looks like you might be able to use the iFrame for your output, and then you can use a JavaScript call to postback the page to rebind the grid maybe.
<html>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" />
<script language="javascript">
// Get a PageRequestManager reference.
var prm = Sys.WebForms.PageRequestManager.getInstance();
// Hook the _initializeRequest event and add our own handler.
prm.add_initializeRequest(InitializeRequest);
function InitializeRequest(sender, args)
{
// Check to be sure this async postback is actually
// requesting the file download.
if (sender._postBackSettings.sourceElement.id == "DownloadFile")
{
// Create an IFRAME.
var iframe = document.createElement("iframe");
// Get the desired region from the dropdown.
var region = $get("Region").value;
// Point the IFRAME to GenerateFile, with the
// desired region as a querystring argument.
iframe.src = "GenerateFile.aspx?region=" + region;
// This makes the IFRAME invisible to the user.
iframe.style.display = "none";
// Add the IFRAME to the page. This will trigger
// a request to GenerateFile now.
document.body.appendChild(iframe);
}
}
</script>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:DropDownList runat="server" ID="Region">
<asp:ListItem Value="N">North Region</asp:ListItem>
<asp:ListItem Value="W">West Region</asp:ListItem>
<asp:ListItem Value="SE">Southeast Region</asp:ListItem>
</asp:DropDownList>
<asp:Button runat="server" ID="DownloadFile" Text="Generate Report" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
The page that handles the download...
protected void Page_Load(object sender, EventArgs e)
{
string FileResponse;
string Region = Request.QueryString["Region"];
// Code here to fill FileResponse with the
// appropriate data based on the selected Region.
Response.AddHeader("Content-disposition", "attachment; filename=report.csv");
Response.ContentType = "application/octet-stream";
Response.Write(FileResponse);
Response.End();
}

Resources