how to get Eval value to string in ItemTemplate - c#

I need to receive data from Eval function to make comparisons, so i've tried this but can't receive anything from Eval, or Bind.
<ItemTemplate>
<%
string auc_id = ((string)Eval("Item_BelongToAuction"));
Guid id = Guid.Empty;
Guid.TryParse(auc_id, out id);
try
{
using (ModeloEntities modelo = new ModeloEntities())
{
var auction_name = (from auctions in modelo.Auctions
where auctions.Auction_ID == id
select auctions).First();
Response.Write(auction_name.Auction_Name);
}
}
catch { }
%>
</ItemTemplate>

Move your logic to the code behind, like this:
protected string GetAuctionName(string auctionId)
{
Guid id = Guid.Empty;
Guid.TryParse(auctionId, out id);
using (ModeloEntities modelo = new ModeloEntities())
{
var auction_name = (from auctions in modelo.Auctions
where auctions.Auction_ID == id
select auctions).First();
return auction_name.Auction_Name;
}
}
<ItemTemplate>
<%# GetAuctionName((string)Eval("Item_BelongToAuction") %>
</ItemTemplate>
Note that Eval is used inside <%# %>, not <% %>.

Related

Binding output from powershell script to gridview in asp.net c#

I'm very new to c# and I expect what I'm trying to do is quite simple-ish but I'm not able to find or follow other examples where output from a powershell array populates a gridview for further manipulation / execution of another script. The process on page load is to run a powershell script, which creates an array of session details which populate a gridview. A second script can then be initiated to interact wit that session (e.g. force a logoff) by way of selection of the gridview row.
Using other examples I have managed to initiate the first powershell execution, which throws the data to a form via:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PowerShellExecution.Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div>
<h1>PowerShell Harness<asp:Label ID="Label1" runat="server" Text="Label" Visible="False"></asp:Label>
</h1>
<asp:TextBox ID="ResultBox" TextMode="MultiLine" Width="1000px" Height="400px" runat="server"></asp:TextBox>
</div>
</asp:Content>
CodeBehind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Management.Automation;
using System.Text;
namespace PowerShellExecution
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Gets the name if authenticated.
if (User.Identity.IsAuthenticated)
Label1.Text = User.Identity.Name;
else
Label1.Text = "No user identity available.";
// Clean the Result TextBox
ResultBox.Text = string.Empty;
// Initialize PowerShell engine
var shell = PowerShell.Create();
// Add the script to the PowerShell object
// shell.Commands.AddScript(Input.Text);
// shell.Commands.AddScript("D:\\Local_Scripts\\sessioncall.ps1");
shell.Commands.AddCommand("c:\\Local_Scripts\\sessioncall.ps1");
// Add Params
// shell.Commands.AddParameter(null,User.Identity.Name);
// shell.Commands.AddParameter("Username", Label1.Text);
shell.Commands.AddArgument(User.Identity.Name);
// Execute the script
var results = shell.Invoke();
// display results, with BaseObject converted to string
// Note : use |out-string for console-like output
if (results.Count > 0)
{
// We use a string builder ton create our result text
var builder = new StringBuilder();
foreach (var psObject in results)
{
// Convert the Base Object to a string and append it to the string builder.
// Add \r\n for line breaks
builder.Append(psObject.BaseObject.ToString() + "\r\n");
}
// Encode the string in HTML (prevent security issue with 'dangerous' caracters like < >
ResultBox.Text = Server.HtmlEncode(builder.ToString());
}
}
}
}
Sessioncall.ps1
$SessionUser = "$($args[0])"
set-brokersite -AdminAddress UKSite
$a = #(Get-BrokerSession -BrokeringUserName $SessionUser | Select-Object UserFullName, BrokeringTime, ClientName,DesktopGroupName, sessionstate, uid, machinename,#{Name='ENV';Expression={'UK'}})
#Pull US Sessions into array
Set-brokersite -AdminAddress USSite
$a += #(Get-BrokerSession -BrokeringUserName $SessionUser | Select-Object UserFullName, BrokeringTime, ClientName,DesktopGroupName, sessionstate, uid, machinename,#{Name='ENV';Expression={'US'}})
If ($a -ne $null){
Write-Output $a | out-string
}
Else {
Write-Output "No User session! Username was $SessionUser"
}
Currently the output is thrown to the textbox as an out-string. I'm struggling in even how to start to data-bind that array output as rows within a gridview. Just need a little hand-holding to get this started!
Thanks in advance!
Paul.
It's been a while since I've dabbled with WebForms, but I found a way to do what you're after...
First off, let's change your PowerShell script slightly. Rather than return a string (which is what | out-string is doing), we can simply return the objects. The shell.Invoke() method in the C# code knows how to extract fully-fledged objects from the output of the script so we don't need to serialize to a string inside the PowerShell script and then try to deserialize that again back to objects inside our C# code.
Ignoring your line-of-business logic for a minute, my script simply returns an array of PSCustomObjects and looks like this:
MyScript.ps1
write-output #(
(new-object PSCustomObject -Property ([ordered] #{
"MyProperty1" = "MyValue1.1"
"MyProperty2" = "MyValue2.1"
"MyProperty3" = "MyValue3.1"
})),
(new-object PSCustomObject -Property ([ordered] #{
"MyProperty1" = "MyValue1.2"
"MyProperty2" = "MyValue2.2"
"MyProperty3" = "MyValue3.2"
}))
);
Now, my C# Page_Load method does this:
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
// Initialize PowerShell engine
var powershell = PowerShell.Create();
// Add the script to the PowerShell object
var script = "c:\\temp\\MyScript.ps1";
powershell.Commands.AddCommand(script);
// Execute the script
var results = powershell.Invoke();
...
and results contains a System.Collections.ObjectModel.Collection<PSObject>. We can't databind that directly to a GridView because the properties are tucked away inside key-value pairs in the Properties member of each PSObject, but if we create a new class it's pretty easy to extract the values into something we can databind:
MyClass.cs
public class MyClass
{
public string MyProperty1 { get; set; }
public string MyProperty2 { get; set; }
public string MyProperty3 { get; set; }
}
and our Page_Load can convert the PSObjects into instances of this class:
Default.aspx.cs
...
var objects = results.Select(
r => new MyClass
{
MyProperty1 = (string)r.Properties["MyProperty1"].Value,
MyProperty2 = (string)r.Properties["MyProperty2"].Value,
MyProperty3 = (string)r.Properties["MyProperty3"].Value,
}
);
this.ResultGrid.DataSource = objects;
this.ResultGrid.DataBind();
}
Then, to display the data you just need a GridView added to your Default.aspx with whatever columns and formatting you want defined:
Default.aspx
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div>
<h1>PowerShell Harness<asp:Label ID="Label1" runat="server" Text="Label" Visible="False"></asp:Label></h1>
<asp:GridView ID="ResultGrid" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="MyProperty1" HeaderText="My Property 1" />
<asp:BoundField DataField="MyProperty2" HeaderText="My Property 2" />
<asp:BoundField DataField="MyProperty3" HeaderText="My Property 3" />
</Columns>
</asp:GridView>
</div>
</asp:Content>
Run that and you should see something like this on the page:
Note
You might find your Get-BrokerSession cmdlet returns a collection of a specific type of object already rather than PSCustomObject, in which case you could possibly skip the conversion step and databind directly to the results object, so you might have to play with that to see. Hopefully the above will give you some pointers if there are any differences.
Hope this helps.
Many thanks for the guidance. Gridview now populates.
protected void Page_Load(object sender, EventArgs e)
{
// Gets the name if authenticated.
if (User.Identity.IsAuthenticated)
Label1.Text = User.Identity.Name;
else
Label1.Text = "No user identity available.";
// Clean the Result TextBox
// Initialize PowerShell engine
var shell = PowerShell.Create();
// Add the script to the PowerShell object
// shell.Commands.AddScript(Input.Text);
// shell.Commands.AddScript("D:\\Local_Scripts\\sessioncall.ps1");
shell.Commands.AddCommand("c:\\Local_Scripts\\sessioncall.ps1");
// Add Params
// shell.Commands.AddParameter(null,User.Identity.Name);
// shell.Commands.AddParameter("Username", Label1.Text);
shell.Commands.AddArgument(User.Identity.Name);
// Execute the script
var results = shell.Invoke();
// display results, with BaseObject converted to string
// Note : use |out-string for console-like output
if (results.Count > 0)
{
// We use a string builder ton create our result text
var results2 = shell.Invoke();
foreach (var psObject in results)
{
// Convert the Base Object to a string and append it to the string builder.
// Add \r\n for line breaks
var UserFullName = (psObject.Members["UserFullName"]);
var BrokeringTime = (psObject.Members["BrokeringTime"]);
var ClientName = (psObject.Members["ClientName"]);
var DesktopGroupName = (psObject.Members["DesktopGroupName"]);
var SessionState = (psObject.Members["SessionState"]);
var Uid = (psObject.Members["Uid"]);
var MachineName = (psObject.Members["MachineName"]);
var ENV = (psObject.Members["ENV"]);
// builder.Append(psObject.BaseObject.ToString() + "\r\n");
}
this.ResultGrid.DataSource = results2;
this.ResultGrid.DataBind();
}
}
Returns
[![enter image description here][1]][1]
However this method throws an exception error when you then define a datakeyname.
<asp:GridView ID="ResultGrid" runat="server" DataKeyNames="uid" AutoGenerateColumns="False" OnSelectedIndexChanged="ResultGrid_SelectedIndexChanged">
<Columns>
<asp:buttonfield buttontype="Button"
commandname="Select"
headertext="View"
text="View"/>
<asp:BoundField DataField="UserFullName" HeaderText="UserFullName" />
<asp:BoundField DataField="BrokeringTime" HeaderText="BrokeringTime" />
<asp:BoundField DataField="ClientName" HeaderText="ClientName" />
<asp:BoundField DataField="DesktopGroupName" HeaderText="DesktopGroupName" />
<asp:BoundField DataField="SessionState" HeaderText="SessionState" />
<asp:BoundField DataField="Uid" HeaderText="Uid" />
<asp:BoundField DataField="MachineName" HeaderText="MachineName" />
<asp:BoundField DataField="ENV" HeaderText="ENV" />
</Columns>
</asp:GridView>
code behind
protected void ResultGrid_SelectedIndexChanged(object sender, EventArgs e)
{
// Determine the RowIndex of the Row whose Button was clicked.
//int rowIndex = ((sender as Button).NamingContainer as GridViewRow).RowIndex;
String key = ResultGrid.SelectedDataKey.Value.ToString();
//Get the value of column from the DataKeys using the RowIndex.
//int id = Convert.ToInt32(ResultGrid.DataKeys[rowIndex].Values[01]);
// Response.Write("IM_RAA_657x_Date.aspx?Day=" + ResultGrid.SelectedDataKey.Value(0) + "&BusinessCategory=" + ResultGrid.SelectedDataKey.Values(1).ToString())
}
This throws an exception error at
this.ResultGrid.DataBind();
"System.Web.HttpException: 'DataBinding: 'System.Management.Automation.PSObject' does not contain a property with the name 'uid'.'"
I'm not clear if the method is now the issue or something outside of that. I'm confused as it must see inside PSObjects correctly in order for the variables to be defined and populate the gridview?! Hmm.
Wow; OK; I just realised this entire section is ignored! Case in point; it can be commented out! So clearly adjust the output from the powershell script!
foreach (var psObject in results)
{
// Convert the Base Object to a string and append it to the string builder.
// Add \r\n for line breaks
//var UserFullName = (psObject.Members["UserFullName"]);
//var BrokeringTime = (psObject.Members["BrokeringTime"]);
//var ClientName = (psObject.Members["ClientName"]);
//var DesktopGroupName = (psObject.Members["DesktopGroupName"]);
//var SessionState = (psObject.Members["SessionState"]);
//var Uid = (psObject.Members["Uid"]);
//var MachineName = (psObject.Members["MachineName"]);
//var ENV = (psObject.Members["ENV"]);
// builder.Append(psObject.BaseObject.ToString() + "\r\n");
}
Forgive me but I'm almost there!
r => new MyClass
{
UserFullName = (string)r.Properties["UserFullName"].Value,
BrokeringTime = (DateTime)r.Properties["BrokeringTime"].Value,
ClientName = (string)r.Properties["ClientName"].Value,
DesktopGroupName = (string)r.Properties["DesktopGroupName"].Value,
//SessionState = (string)r.Properties["SessionState"].Value,
Uid = (Int64)r.Properties["Uid"].Value,
//MachineName = (string)r.Properties["MachineName"].Value,
//ENV = (string)r.Properties["ENV"].Value,
}
);
this.ResultGrid.DataSource = objects;
this.ResultGrid.DataBind();
}
}
protected void ResultGrid_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write(ResultGrid.SelectedValue.ToString());
}
}
internal class MyClass
{
public string UserFullName { get; set; }
public DateTime BrokeringTime { get; set; }
public string ClientName { get; set; }
public string DesktopGroupName { get; set; }
public String SessionState { get; set; }
public Int64 Uid { get; set; }
public string MachineName { get; set; }
public string ENV { get; set; }
}
So I'm now correctly populating the gridview; Some columns are still being problematic and are not being treated as strings BUT I'm almost there!
Looks like Get-member type:
BrokeringTime NoteProperty datetime BrokeringTime=28/02/2020 06:56:39
ClientName NoteProperty string ClientName=clientname
DesktopGroupName NoteProperty string DesktopGroupName=desktopgroupname
ENV NoteProperty System.String ENV=UK
MachineName NoteProperty string MachineName=machinename
SessionState NoteProperty SessionState SessionState=Active
Uid NoteProperty long Uid=12345678
UserFullName NoteProperty string UserFullName=username
C# Does seem to like system.string.

Can I check a query string in an anchor tag before the anchor tag is clicked on the parent page? If so, how?

In my application FirstPage.aspx I am using a repeater to create a series of links:
<a href="MySecondPage.aspx?id=<%#DataBinder.Eval(Container.DataItem, "ValueID")%>">
<%#DataBinder.Eval(Container.DataItem, "ValueName")%></a>
Normally, in the page load of MySecondPage.aspx I would get the value of the QueryString like:
string OldID = Request.QueryString["id"];
num SkulloID = Convert.ToInt(SkulloID);
if(SkulloID > 5)
{
Response.Write("Hello World");
}
Instead of this, what I want to do is somehow on FirstPage.aspx get the value of the querystring in the anchor tag to do some logic on just as in the case of MySecondPage.aspx. Is something like this possible?
Edited to test solutions presented
#CodingBiz I tried the solution you presented and I am having trouble. Here is what I have tried.
In the Page_Load i added the following code to set the CommandArgument of the link button
//Error: The name containder does not exist in the current context
lbnTestLink.CommandArgument = DataBinder.Eval(container.DataItem, "ValueID");
In the asp:LinkButton click command
MyID = DataBinder.Eval(container.DataItem, "ValueID");
using (SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString))
{
SqlCommand cmdzero = new SqlCommand(#"SELECT [num] FROM [My_Table] Where [ValueID] = #MyID AND [IsSubItem] = 1 AND [FiscalYear] = #FiscalYear", conn2);
cmdzero.Parameters.AddWithValue("#MyID", MyID);
cmdzero.Parameters.AddWithValue("#FiscalYear", strFiscalYear);
conn2.Open();
int countzero = (int)cmdzero.ExecuteScalar();
int myArgument = countzero;
if (MyID = myArgument)
{
strListLink = "FistPage.aspx";
}
else
{
strListLink = "SecondPage.aspx?id=<%#DataBinder.Eval(Container.DataItem, \"ValueID\")%>";
}
}
I don't understand where the querystring is supposed to get set here.

How i can generate dynamic id for text field and get data from array of model in asp.net 4 mvc3

This is my first post here! :)
I have to return an array of my model from my controller class to the view page. I want to put the data into a text box and generate dynamic id's for each text box to use the data further via JavaScript (that's why I am looking for dynamic id's).
Model
public partial class BhBuyerChart
{
public string Date { get; set; }
public string Quantity { get; set; }
public BhBuyerChart(string n, string d)
{
Date = n;
Quantity = d;
}
}
Controller
public ActionResult test()
{
BhBuyerChart[] model = new BhBuyerChart[7];
DataTable dt = (DataTable)ExecuteDB(ERPTask.AG_GetAllShipmentRecord, CurrentUserId);
List<BhBuyerChart> ItemList = null;
ItemList = new List<BhBuyerChart>();
int i = 0;
foreach (DataRow dr in dt.Rows)
{
model[i] = new BhBuyerChart(dr["Shipmentdate"].ToString(), dr["ShipmentQuantity"].ToString());
i++;
};
return View(model);
}
View
1st Attempt
<div>
<% for (int i=0; i<2; i++) {%>
<%: Html.TextBoxFor(m => m[i].Quantity, new { id = "Quantity"})%> <%--value can assign from model but dnt know how to assing dynamic id --%>
<input type="text" value="<%= i %>" id="text<%=i %>"/> <%--dynamic id can be assinged dnt knw how to assing model value here in textbox --%>
<% } %>
</div>
2nd Attempt
<div>
<% int i = 0; %>
<% foreach (ERP.Domain.Model.BhBuyerChart user in Model) { %>
<% i++; %>
<input type="text"; id="textbox<% i %>" ; value="<% user.Quantity %>" />
<% } %>
</div>
I really appreciate everybody's attention and help and I look forward to your responses!
I think this should do it for you. Effectively what you're going to do is build a new method inside the controller so that you can POST back to the controller with the updated values. Further, you don't want the Quantity fields to have different names because they won't bind - and so each one you build will say Quantity in the name and id attribute when the HTML is generated.
If I've misunderstood your need please comment.
Controller
public ActionResult test()
{
BhBuyerChart[] model = new BhBuyerChart[7];
DataTable dt = (DataTable)ExecuteDB(ERPTask.AG_GetAllShipmentRecord, CurrentUserId);
List<BhBuyerChart> ItemList = null;
ItemList = new List<BhBuyerChart>();
int i = 0;
foreach (DataRow dr in dt.Rows)
{
model[i] = new BhBuyerChart(dr["Shipmentdate"].ToString(), dr["ShipmentQuantity"].ToString());
i++;
};
return View(model);
}
[HttpPost]
public ActionResult test(ICollection<BhBuyerChart> charts)
{
// This allows you to POST to the controller with the modified values
// Note that based on what you're collecting client side the charts
// will ONLY contain the Quantity value, but they will all have one.
// If you need the date you can either show a text box for that or
// even place the date inside a hidden field.
}
View
<form method="post" action="/{controllername}/test">
...
<div>
<% for (int i=0; i<2; i++) {%>
<!-- This line will both bind the value and allow you to POST -->
<!-- this form back to the controller with the new values -->
<!-- NOTE: each control is actually going to be named the same -->
<!-- but when it's posted will post in order to the collection -->
<%: Html.TextBoxFor(m => m[i].Quantity) %>
<!-- You may or may not want this here so that you can get the -->
<!-- value of the date back to the server during a POST -->
<%: Html.HiddenFor(m => m[i].Date) %>
<% } %>
</div>
...
</form>
JavaScript
Now in JavaScript what you can do is use jQuery to simply get a listing of all the elements named Quantity like this and use them from that array.
// with this ([0].Quantity) being the template
// we'll use a simple wildcard selector to find
// all of them that end with Quantity.
var elems = $("[name$=Quantity]")
// now you have a list of the elements that you
// can use to populate the other array with -
// getting the value with a statement like...
var val = elems[0].val();
You need the excellent extension made by Steven Sanderson called BeginCollectionItem. For each row in your Model, each inputs will inherit an unique guid that you can reuse for validation or other stuff.
For more information on how to use the extension step by step, please go see the article on Steven Sanderson's blog : Editing a variable length list, ASP.NET MVC 2-style
The article was made for MVC2 but it work in MVC3 too. It should work in MVC4 but i haven't tested yet.
View
<% foreach (var item in Model) {
<% using(Html.BeginCollectionItem("bhBuyerItem")) { %>
<%= Html.TextBoxFor(m => m.Quantity) %>
<%= Html.TextBoxFor(m => m.Date) %>
<% } %>
<% } %>
The extension method
public static class HtmlPrefixScopeExtensions
{
private const string idsToReuseKey = "__htmlPrefixScopeExtensions_IdsToReuse_";
public static IDisposable BeginCollectionItem(this HtmlHelper html, string collectionName)
{
var idsToReuse = GetIdsToReuse(html.ViewContext.HttpContext, collectionName);
string itemIndex = idsToReuse.Count > 0 ? idsToReuse.Dequeue() : Guid.NewGuid().ToString();
// autocomplete="off" is needed to work around a very annoying Chrome behaviour whereby it reuses old values after the user clicks "Back", which causes the xyz.index and xyz[...] values to get out of sync.
html.ViewContext.Writer.WriteLine(string.Format("<input type=\"hidden\" name=\"{0}.index\" autocomplete=\"off\" value=\"{1}\" />", collectionName, html.Encode(itemIndex)));
return BeginHtmlFieldPrefixScope(html, string.Format("{0}[{1}]", collectionName, itemIndex));
}
public static IDisposable BeginHtmlFieldPrefixScope(this HtmlHelper html, string htmlFieldPrefix)
{
return new HtmlFieldPrefixScope(html.ViewData.TemplateInfo, htmlFieldPrefix);
}
private static Queue<string> GetIdsToReuse(HttpContextBase httpContext, string collectionName)
{
// We need to use the same sequence of IDs following a server-side validation failure,
// otherwise the framework won't render the validation error messages next to each item.
string key = idsToReuseKey + collectionName;
var queue = (Queue<string>)httpContext.Items[key];
if (queue == null) {
httpContext.Items[key] = queue = new Queue<string>();
var previouslyUsedIds = httpContext.Request[collectionName + ".index"];
if (!string.IsNullOrEmpty(previouslyUsedIds))
foreach (string previouslyUsedId in previouslyUsedIds.Split(','))
queue.Enqueue(previouslyUsedId);
}
return queue;
}
private class HtmlFieldPrefixScope : IDisposable
{
private readonly TemplateInfo templateInfo;
private readonly string previousHtmlFieldPrefix;
public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix)
{
this.templateInfo = templateInfo;
previousHtmlFieldPrefix = templateInfo.HtmlFieldPrefix;
templateInfo.HtmlFieldPrefix = htmlFieldPrefix;
}
public void Dispose()
{
templateInfo.HtmlFieldPrefix = previousHtmlFieldPrefix;
}
}
}
well after several tries i guess i have able to make this
<%for (int i = 0; i <= 1; i++)%>
<% { %>
<div style="width:100%; float:left">
<%: Html.TextBoxFor(m => m[i].Date, new { id= i+500 })%>
<%: Html.TextBoxFor(m => m[i].Quantity, new { id = i })%>
<%: Html.TextBoxFor(m => m[i].Quantity) %>
</div>
<script type="text/javascript">
var val = [[], []];
for (k = 0; k <= 1; k++) {
val[k][0] = document.getElementById(k+300).value;
val[k][1] = parseInt(document.getElementById(k).value);
}
</script>
this gonna take dynamic data from model array and create dynamic id for each textbox and assign them into variable using dynamic id

how to store htmltable into session variable

i have a html table which i want to pass to another page using session variable,how can it be done? I have tried this
Session["sumtable"] = (HtmlTable)htab;
Its not working...
On the other page
.aspx
<table id="tblsum" runat="server"></table>
.cs
if (Session["sumtable"] != null)
{
tblsum = (HtmlTable)Session["sumtable"];
}
Try this
//Page Source
Session["tbl"] = dt.Rows; // table id = td
Response.Redirect("WebForm4.aspx");
// page Destination
HtmlTableRowCollection tr = (HtmlTableRowCollection)Session["tbl"];
foreach (HtmlTableRow t in tr)
{
dt.Rows.Add(t); // table id = td
}

Using Programmatic Images in Nivo SLider with asp.net and c#

"Only images or images wrapped in links are allowed in the slider div. Any other HTML will break the slider."
What would be the best way to programatically insert images from a database in c#?
I was using a label inside the div id="slider" tag but then realized the label would create the images within a span tag and therefore break the slider.
lblSlider.Text += "<img src=\"" + URL + "\" alt=\"" + address + "\" title=\"<a href='Featured/" + address" + address + ", " + city + "</a>\" />";
Use markup like this...
<img src='ImageHandler.ashx?ProductID=<%# Eval("ProductID")%>'
alt="<%# Eval("ProductName") %>" title="<%# Eval("ProductName") %>" />
... in conjunction with an image HttpHandler class like this (adapt for your own particular DB schema):
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["productID"] != null)
{
try
{
string ProductID = context.Request.QueryString["ProductID"];
if (Convert.ToInt32(ProductID) > 0)
{
const string CONN
= "Initial Catalog=xxx;Data Source=xxx;Integrated Security=SSPI;";
string selectQuery
= "SELECT Photo FROM dbo.Products WHERE dbo.Products.ProductID="
+ ProductID.ToString();
SqlConnection conn = new SqlConnection(CONN);
SqlCommand cmd = new SqlCommand(selectQuery, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
dr.Close();
conn.Dispose();
// context.Response.End();
// caused an "Abort thread" error
// - this is correct and is a special exception
}
}
catch (Exception ex)
{
ErrorReporting.LogError(ex);
}
}
else
throw new ArgumentException("No ProductID parameter specified");
}
public bool IsReusable
{
get
{
return true; // multiple images otherwise false
}
}
}
Okay, I haven't tried the other solution but I did this and it works:
Here are some global c# variables:
protected int count;
protected string[] arr = new string[20];
Then I assign values to the string array from my database in the Page_Load method.
And then I just write the nivo slider with javascript on my page:
<script type="text/javascript">
document.write("<div id='slider' class='nivoSlider'>");
var count = <%= count %>;
var myArray = <% = new JavaScriptSerializer().Serialize(arr) %>;
for(var i = 0; i < count; i++) {
document.write(myArray[i]);
}
document.write("</div>");
</script>
This solution seems easier to me, but if anyone thinks I should use the other solution over this one, let me know. Oh, and don't forget the namespace System.Web.Script.Serialization
I have same requirement and tried the below code to accomplish the dynamic loading of images basing on category. These image loaded from my database. I am new to ASP.Net please let me know if I did anything wrong or did any blunders :).
in ASP.Net file:
I am using nivo slider append method
<script type="text/javascript">
$(window).load(function() {
$('#slider').append('<img id="ad5" src=<%=__ad1ImageUrl %> />');
$('#slider').append('<img id="ad6" src=<%=__ad2ImageUrl %> />');
$('#slider').append('<img id="ad7" src=<%=__ad3ImageUrl %> />');
$('#slider').append('<img id="ad8" src=<%=__ad4ImageUrl %> />');
$('#slider').nivoSlider();
});
</script>
My table looks like this:
<table style="height: 183px; width: 100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td align="left">
<div id="wrapper">
<div class="slider-wrapper theme-default">
<div class="ribbon">
</div>
<div id="slider" class="nivoSlider">
<!-- note that no images added here -->
</div>
</div>
</div>
</td>
</tr>
</table>
In the code behind:
Use variable to store image url(s). You can now get the URL(s) from DB and get populated. In my code i have used these variables (can use array also) to capture url path. You can get the paths from any source like Database, Xml or ...
public string __ad1ImageUrl = "";
public string __ad2ImageUrl = "";
public string __ad3ImageUrl = "";
public string __ad4ImageUrl = "";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
__ad1ImageUrl = "UserControls/Images/mainBanner1.jpg";
__ad2ImageUrl = "UserControls/Images/mainBanner2.jpg";
__ad3ImageUrl = "UserControls/Images/mainBanner3.jpg";
__ad4ImageUrl = "UserControls/Images/mainBanner4.jpg";
}
}

Categories