For the solution, I cannot use any postback methods, because this is all working through ajax. The solution need to be implemented in the asp.net code.
I have a List<WebPage> that contains a list of Links (List<Link>) and I need for all the links to bind repetitive information such as page title, id, url. Here is my current repeater.
<div id="result">
<asp:Repeater runat="server" id="results">
<Itemtemplate>
<asp:Repeater runat="server" datasource='<%# Eval("Links") %>'>
<Itemtemplate>
<tr class="gradeX odd">
<td><%# Eval("Id") %></td> //property of WebPage (part of results repeater)
<td><%# Eval("Title") %></td> //property of WebPage (part of results repeater)
<td><%# Eval("Url") %></td> //property of WebPage (part of results repeater)
<td><%# Eval("URL") %></td>//Property of Link
<td><%# Eval("URLType") %></td> //Property of Link
<td><%# Eval("URLState") %></td> //Property of Link
</tr>
</Itemtemplate>
</asp:Repeater>
</Itemtemplate>
</asp:Repeater>
</div>
of course this doesnt work, how can i do this?
Thanks for your help!
I'm assuming the problem you're trying to solve here is how to include properties from multiple levels in a nested object-- some properties from the top level but other properties from the lower level. One easy way to do this is to transform the inner collection into a new type which contains a mix of all the properties you need.
Here's a code sample illustrating this technique using IEnumerable.Select and C# Anonymous Classes to create a new class:
<%# Page Title="Home Page" Language="C#" %>
<div id="result">
<asp:Repeater runat="server" id="results">
<ItemTemplate>
<asp:Repeater runat="server" datasource='<%# ((WebPage)Container.DataItem).Links.Select ( link => new {
Id = ((WebPage)Container.DataItem).Id,
Title = ((WebPage)Container.DataItem).Title,
Url = ((WebPage)Container.DataItem).Url,
URL = link.URL,
URLType = link.URLType,
URLState = link.URLState
}) %>'>
<ItemTemplate>
<tr class="gradeX odd">
<td><%# Eval("Id") %></td> <!--property of WebPage (part of results repeater) -->
<td><%# Eval("Title") %></td> <!--property of WebPage (part of results repeater) -->
<td><%# Eval("Url") %></td> <!--property of WebPage (part of results repeater) -->
<td><%# Eval("URL") %></td><!--Property of Link -->
<td><%# Eval("URLType") %></td> <!--Property of Link-->
<td><%# Eval("URLState") %></td> <!--Property of Link -->
</tr>
</ItemTemplate>
</asp:Repeater>
</Itemtemplate>
</asp:Repeater>
</div>
<script runat="server">
public class Link
{
public string URL { get; set; }
public int URLType { get; set; }
public int URLState { get; set; }
}
public class WebPage
{
public string Id { get; set; }
public string Title { get; set; }
public string Url { get; set; }
public List<Link> Links { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
WebPage[] pages = new WebPage[]
{
new WebPage { Id = "foo",
Title = "foobar",
Url = "http://foo.bar",
Links = new List<Link> ( new Link[] {
new Link {URL = "http://something", URLType = 1, URLState = 2},
new Link {URL = "http://someotherthing", URLType = 3, URLState = 4}
})
},
new WebPage { Id = "excellent",
Title = "excellent Title",
Url = "http://excellent.com",
Links = new List<Link> ( new Link[] {
new Link {URL = "http://excellent", URLType = 5, URLState = 6},
new Link {URL = "http://totallyexcellent", URLType = 7, URLState = 8}
})
}
};
results.DataSource = pages;
results.DataBind();
}
</script>
Related
I have a repeater inside an html table that uses pagination. I want to be able to read the values of the hidden fields within the repeater in the code behind, but only the hidden field values of the table page being viewed on postback seem to be set when I'm in the code behind. How do I make it so the hidden field values are set for each repeater item regardless of the table page?
HTML:
<div id="divTableContainer" runat="server">
<table id="tblAssessmentExtracts" class="table table-striped table-sm table-hover ">
<thead>
<tr>
<th>Consumer</th>
<th>Assessment</th>
<th>Completed</th>
<th></th>
</tr>
</thead>
<tbody>
<asp:Repeater ID="rptAssessmentExtractQueue" runat="server" OnItemCommand="rptAssessmentExtractQueue_ItemCommand">
<ItemTemplate>
<tr class="assessment-extract-block">
<td><%# Eval("ConsumerName") %>
</td>
<td><%# Eval("SurveyName") %>
</td>
<td><%# Eval("CompletionDate") %></td>
<td class="buttoncell">
<asp:LinkButton ID="btnExportRecord" runat="server" Text="Export" CommandArgument='<%# Eval("Id") %>' />
<asp:HiddenField ID="hdAssessmentId" runat="server" Value='<%# Eval("Id") %>' />
<span class="selection"><asp:HiddenField ID="hdAssessmentSelected" runat="server" /></span>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</tbody>
</table>
</div>
JavaScript:
<script type="text/javascript">
$(document).ready(function () {
var table = $('#tblAssessmentExtracts').DataTable({
"pageLength": 25,
});
});
function selectBlock(elementIndex, element) {
var selectedField = $(element).find('.selection input[type="hidden"]');
if ($(element).hasClass("table-info") === false) {
$(element).addClass("table-info");
}
if (selectedField.length > 0) {
selectedField.val("true");
}
}
function deselectBlock(elementIndex, element) {
var selectedField = $(element).find('.selection input[type="hidden"]');
if ($(element).hasClass("table-info")) {
$(element).removeClass("table-info");
}
if (selectedField.length > 0) {
selectedField.val("");
}
}
$('.assessment-extract-block').click(function (e) {
var selectedField = $(this).find('.selection input[type="hidden"]');
if (selectedField.length > 0) {
if (selectedField.val() === "true") {
deselectBlock(0, $(this));
} else {
selectBlock(0, $(this));
}
}
});
</script>
C#:
private IEnumerable<long> getSelectedResponses()
{
List<long> assessmentIds = new List<long>();
foreach (RepeaterItem riAssessment in rptAssessmentExtractQueue.Items)
{
HiddenField hdAssessmentSelected = riAssessment.FindControl("hdAssessmentSelected") as HiddenField;
HiddenField hdAssessmentId = riAssessment.FindControl("hdAssessmentId") as HiddenField;
bool export = false;
if (bool.TryParse(hdAssessmentSelected.Value, out export) && export)
{
long assessmentId;
if (long.TryParse(hdAssessmentId.Value, out assessmentId) && assessmentId > 0)
{
assessmentIds.Add(assessmentId);
}
}
}
return assessmentIds;
}
I have written a code to fetch news from a website.
The code includes UI page in which i am inserting name of website (from which data to be fetched) & on button click event it fetches the news.
The code is as follows :
<form runat="server" style="margin-left:10px;">
<br /><br />
<asp:TextBox ID="txtSiteName" runat="server"></asp:TextBox> <asp:Button ID="btnSubmit" runat="server" Text="Get News" OnClick="btnSubmit_Click"/><br /><br /><br />
<h3>Here are the latest news</h3><br />
<div style="max-height: 350px; overflow: auto">
<asp:GridView ID="gvRss" runat="server" AutoGenerateColumns="false" ShowHeader="false" Width="90%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table width="100%" border="0" cellpadding="0" cellspacing="5">
<tr>
<td>
<asp:CheckBox ID="cbxAddNews" runat="server" />
</td>
<td>
<h3 style="color: #3E7CFF"><%#Eval("Title") %></h3>
</td>
<td width="200px">
<%#Eval("PublishDate") %>
</td>
</tr>
<tr>
<td colspan="2">
<hr />
<%#Eval("Description") %>
</td>
</tr>
<tr>
<td> </td>
<td align="right">
Read More...
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
The codebehind is as follows :
public class Feeds
{
public string Title { get; set; }
public string Link { get; set; }
public string PublishDate { get; set; }
public string Description { get; set; }
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
PopulateRssFeed();
}
private void PopulateRssFeed()
{
//string RssFeedUrl = "https://realty.economictimes.indiatimes.com/rss/topstories";
string RssFeedUrl = txtSiteName.Text;
List<Feeds> feeds = new List<Feeds>();
try
{
XDocument xDoc = new XDocument();
xDoc = XDocument.Load(RssFeedUrl);
var items = (from x in xDoc.Descendants("item")
select new
{
title = x.Element("title").Value,
link = x.Element("link").Value,
pubDate = x.Element("pubDate").Value,
description = x.Element("description").Value
});
if (items != null)
{
foreach (var i in items)
{
Feeds f = new Feeds
{
Title = i.title,
Link = i.link,
PublishDate = i.pubDate,
Description = i.description
};
feeds.Add(f);
}
}
gvRss.DataSource = feeds;
gvRss.DataBind();
}
catch (Exception ex)
{
throw;
}
}
what it does is it takes all the news from one particular website on button click event.
But i want to implement the same functionality using the scheduler! (want to eliminate button click event instead!)
Since i haven't worked on scheduler before, can anyone help me out or any suggestions as how to fetch the data (news) from multiple websites using scheduler & store it in database table instead of directly displaying them??
At client side use setInterval(expression, timeout);.
1) Create a WebMethod at you webpage.
[WebMethod]
public static void UpdateNews()
{
PopulateRssFeed();
}
2) Create a method at client side so that use Ajax to call that WebMethod.
var updateNews = function(){ $.ajax({ type: "POST", url:"YourWebpage.aspx/UpdateNews", contentType: "application/json; charset=utf-8" });}
3) Use SetInterval and call your client side ajax method
setInterval(updateNews(), 5000);//every 5 second
I am creating dynamically an array, adding a line for each entry of some data. Each entry must have a button to do some stuff with it, but I am stuck at this point. I have this code to create the ASP.NET button:
<asp:Button ID="buttonyes" class="buttonyes" CommandArgument='<%= request.ID %>'
CommandName="AcceptRequest" OnClick='<%= ButtonPressed %>' runat="server"/>
But when I run it, I have multiple errors saying that:
The %= and < or > expressions are not valid.
When I click on the button, I want to call a function written in the index.aspx.cs file linked with my index.aspx, here is ButtonPressed function and with a filter in this function, it choose what action it should do:
protected void ButtonPressed(Object sender, CommandEventArgs e)
{
Button btn = (Button)sender;
switch (btn.CommandName)
{
case "AcceptRequest":
AcceptRequest(btn.CommandArgument.ToString());
break;
case "RefuseRequest":
RefuseRequest(btn.CommandArgument.ToString());
break;
}
}
The problem is that I don't succeed in passing those C# variables as a CommandArgument and CommandName.
I already tried those syntaxes, following some previous questions:
CommandArgument="<%: request.ID %>"
CommandArgument='<%: request.ID %>'
CommandArgument="<%= request.ID %>"
CommandArgument='<%= request.ID %>'
But none of them worked.
EDIT 1:
As #grek40 said below, the OnClick value should be replace like the following:
<asp:Button ID="buttonyes" class="buttonyes" CommandArgument='<%= request.ID %>'
CommandName="AcceptRequest" OnCommand="ButtonPressed" runat="server"/>
EDIT 2:
I would like to know how to pass a C# local variable since those button should be added in a foreach loop like so:
foreach (Request request in requests)
{
%>
<tr>
<td><%: request.applicant.Name + " (" + request.applicant.ID + ")" %></td>
<td><%: request.software.Name %></td>
<td><%: request.date %></td>
<td class="actions">
<asp:Button ID="buttonyes" class="buttonyes" CommandName="AcceptRequest" CommandArgument="<# request.Id %>" OnCommand="ButtonPressed" runat="server"/>
<asp:Button ID="buttonno" class="buttonno" CommandName="RefuseRequest" CommandArgument="<# request.Id %>" OnCommand="ButtonPressed" runat="server"/>
</td>
</tr>
<%
}
By the way, the code above doesn't work, since, as #Nino said, this only works for global variables.
Why not save yourself a whole lot of trouble and switch to a Strongly Typed Repeater Control. You can make it type safe with the ItemType property. The value must the the complete namespace to the class request
Then you will still be able to access the properties like you have now. But instead of using request, you use the fixed name of Item.
<table border="1">
<asp:Repeater ID="Repeater1" runat="server" ItemType="Namespace1.Default1.request">
<ItemTemplate>
<tr>
<td><%# Item.applicant.Name + " (" + Item.applicant.ID + ")" %></td>
<td><%# Item.software.Name %></td>
<td><%# Item.date.ToLongDateString() %></td>
<td class="actions">
<asp:Button ID="buttonyes" class="buttonyes" CommandName="AcceptRequest" CommandArgument='<%# Item.Id %>' OnCommand="ButtonPressed" runat="server" />
<asp:Button ID="buttonno" class="buttonno" CommandName="RefuseRequest" CommandArgument='<%# Item.Id %>' OnCommand="ButtonPressed" runat="server" />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
Now you can use the normal way of databinding: CommandArgument='<%# Item.Id %>'
Below the full code for testing...
public List<request> requests = new List<request>();
protected void Page_Load(object sender, EventArgs e)
{
//create some dummy data
for (int i = 0; i < 10; i++)
{
request r = new request() { Id = i, date = DateTime.Now };
r.applicant = new applicant() { Name = "Applicant " + i, ID = 1 + 100 };
r.software = new software() { Name = "Software " + i };
requests.Add(r);
}
if (!Page.IsPostBack)
{
Repeater1.DataSource = requests;
Repeater1.DataBind();
}
}
public class request
{
public int Id { get; set; }
public DateTime date { get; set; }
public applicant applicant { get; set; }
public software software { get; set; }
}
public class applicant
{
public int ID { get; set; }
public string Name { get; set; }
}
public class software
{
public int ID { get; set; }
public string Name { get; set; }
}
you can do it like this:
CommandArgument='<%# request.ID %>'
That way CommandArgument will be assigned during DataBidning phase.
I think you have the command action incorrect.
Most people might think OnClick(), but your method signature is associated with OnCommand()
Change from
OnClick='<%= ButtonPressed %>'
to
OnCommand='<%= ButtonPressed %>'
The OnClick signature is ( object sender, EventArgs e )... OnCommand signature is ( object sender, CommandEventArgs e)... and the expected parameter value should be good.
As for the "OnClick" or "OnCommand", that should be fixed based on the function that will handle the call, such as your "ButtonPressed" method. You do NOT need your "%" wrappers as the function is not changing... your COMMAND NAME can change, but not the method that handles the event...
OnClick='ButtonPressed'
I'm making a website to show various statistics regarding games.
I got two seperate tables in an sql-database. One called PlayerMatch and another called Match.
The two columns I want to compare is TeamId in PlayerMatch (PlayerMatch.TeamId vs. WinningTeamId in Match (Match.WinningTeamId)
To show it all, I have made a table, where I have placed some asp:repeaters inside.
Here is one of them, as they are all essentially the same.
<asp:Repeater ID="repHighGPM" runat="server">
<ItemTemplate>
<td><%#Eval("Match.MatchNumber") %></td>
<td><%#Eval("Match.WinningTeamId") %></td>
<td><%#Eval("Name") %></td>
<td>
<img src=' <%#Eval("Image") %>' /></td>
<td><%#Eval("GoldPerMinute") %></td>
</ItemTemplate>
</asp:Repeater>
Now, the problem is that as it is now it will only show the Id of the team who won (Match.WinningTeamId). But not if the player was on that team. So essentially it just needs to check if PlayerMatch.TeamId == Match.WinningTeamId. And if that is true it should write "won match", while false will be "lost match"
Any ideas? I know it should be some kind of if-else function, but I have no idea how to do it.
You could use the inner join in sql query :
make a datasource to your databse write the query after that add the datasource to repeater DataSourceID="" ....
<asp:Repeater ID="repHighGPM" runat="server" DataSourceID="match">
<ItemTemplate>
<td><%#Eval("Match.MatchNumber") %></td>
<td><%#Eval("Match.WinningTeamId") %></td>
<td><%#Eval("Name") %></td>
<td>
<img src=' <%#Eval("Image") %>' /></td>
<td><%#Eval("GoldPerMinute") %></td>
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="match" runat="server" ConnectionString="<%$ ConnectionStrings:database %>" SelectCommand="select m.match number, m.winningTeamID, Name ,Image from Match m inner join
playermatch p on p.Teamid = m.WinningTeamId"></asp:SqlDataSource>
for more information about inner join read this article :
http://www.w3schools.com/sql/sql_join_inner.asp
I have solved the problem with the following solution:
public string MatchResult (object Result) {
int id = Convert.ToInt32(Request.QueryString["id"]);
DOTA2DataContext db = new DOTA2DataContext();
var Victory = Result;
var TeamId = db.PlayerMatches.Where(x => x.TeamId == id);
var WinningTeam = db.Matches.Where(x => x.WinningTeamId == id);
{
if (TeamId == WinningTeam)
{
return "Won match";
}
else
{
return "Lost match";
}
}
}
And the repeater.
<asp:Repeater ID="repHighD" runat="server">
<ItemTemplate>
<td><%#Eval("Match.MatchNumber") %></td>
<td><%# MatchResult(Eval("Match.WinningTeamId"))%></td>
<td><%#Eval("Hero.Name") %></td>
<td>
<img src=' <%#Eval("Hero.Image") %>' /></td>
<td><%#Eval("Denies") %></td>
</ItemTemplate>
</asp:Repeater>
The following is the design.
<table>
<tr>
<td>Project Title</td>
<td>Download Link</td>
</tr>
<tr>
<td><asp:Label ID="dlLbl" runat="server"></asp:Label></td>
<td><asp:Label ID="dlLink" runat="server"></asp:Label></td>
</tr>
</table>
And the following is the backend codes.
foreach (SPListItem objInnovationListItem in objInnovationList.Items)
{
if (Convert.ToString(objInnovationListItem["Innovation Approval Status"])== status)
{
countStatus++;
//Displays name of the document and download link
dlLbl.Text = objInnovationListItem["Project Title"].ToString();
dlLink.Text = "<a href='/RIDepartment/Innovation%20Submission/" + objInnovationListItem.File.Name + "'>Download</a><br>";
}
}
Hence, my question is, what can I do to allow the tables to dynamically accommodate the document and dl link when there's more than 1 in the loop?
Appreciate some code samples.
With your code style (manual creating html without web-controls) i recommend you to look on ASP.NET MVC side. But i can answer to your question:
First - you need to use asp:Repeater like this:
<table>
<tr>
<td>Project Title</td>
<td>Download Link</td>
</tr>
<asp:Repeater ID="repLinks" runat="server"
onitemdatabound="repLinks_ItemDataBound">
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lblProject" runat="server" Text="Label"></asp:Label>
</td>
<td>
<asp:HyperLink ID="hlLink" runat="server">HyperLink</asp:HyperLink>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
second: you need to initialize your collection, that you want to display. For example: you want to display a collection of objInnovationListItem class:
public class objInnovationListItem
{
public string Name { get; set; }
public string Title { get; set; }
public override string ToString()
{
return Title;
}
}
you need do next:
// list - it's source List<objInnovationListItem>
var bindList = list.Where(p => objInnovationListItem["Innovation Approval Status"] == status); // filter your collection - replace you foreach and if statement
repLinks.DataSource = bindList; // set to repeater your displayed collection
repLinks.DataBind(); // bind your collection
and last - you need to indicate in your Repeater ItemTemplate how to display your objInnovationListItem instance - subscribe to event of your Repeater ItemDataBound:
protected void repLinks_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var item = e.Item.DataItem as objInnovationListItem;
((Label) e.Item.FindControl("lblProject")).Text = item.Name;
((HyperLink) e.Item.FindControl("hlLink")).NavigateUrl = string.Format("/downloaduri?id={0}", item.Title);
}
Result will look like that:
I would use a repeater... Something like this (code might not be exact):
<table>
<tr>
<td>Project Title</td>
<td>Download Link</td>
</tr>
<asp:Repeater id="rptItems" runat="server">
<ItemTemplate>
<tr>
<td><asp:Label ID="dlLbl" runat="server"></asp:Label></td>
<td>Download<br></td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
and then in the ItemDataBound event of the repeater, do something like this:
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
((Label)e.Item.FindControl("dlLbl")).Text= ((SPListItem)e.Item.DataItem)["Project Title"].ToString();
}
Why don't you skip the server side controls, and just write the actual html?
Include this div in your aspx file:
<div runat="server" id="divTable"></div>
And put this in your Page_Load():
StringBuilder sb = new StringBuilder();
sb.Append("<table><tr><td>Project Title</td><td>Download Link</td></tr>");
for (int i = 0; i < 10; i++)
{
sb.AppendFormat("<tr><td>{0}</td><td><a href='{1}'>{1}</a></td></tr>", "Title", "Link");
}
sb.Append("</table>");
divTable.InnerHtml = sb.ToString();
You'll of course need to replace "Title" and "Link" with the appropriate values.
Your other options is to actually create new labels and links, but ASP.net is notoriously difficult to work with when you create your server side controls dynamically.