Checking a query Result in ASP - c#

In my database i have a Table called News. In News i have a column named Link. This link CAN be null. If the article is written by the editors the link will be null , if the editors just want to reference an article from another site then this Link will contain a value.
My task: Make a href to the article. Here i have a problem if my editor writes the article i put a href to that article . If it is not written(so the link is not null) i have to pur that href insteaf.
I have no idea how to do this, any tips ?
Code:
Display:
<asp:DropDownList ID="DropDownSelect" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="DropDownSelect_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="DesDate"> Descending Date </asp:ListItem>
<asp:ListItem Value="AsDate"> Ascending Date </asp:ListItem>
<asp:ListItem Value="AsAlp"> Ascending Alphabetical </asp:ListItem>
<asp:ListItem Value="DesAlp"> Descending Alphabetical </asp:ListItem>
</asp:DropDownList>
<asp:ListView ID="productList" runat="server"
DataKeyNames="NewsID" GroupItemCount="1"
ItemType="SiteStiri.Models.News" SelectMethod="GetProducts">
<EmptyDataTemplate>
<table >
<tr>
<td>No data was returned.</td>
</tr>
</table>
</EmptyDataTemplate>
<EmptyItemTemplate>
<td/>
</EmptyItemTemplate>
<GroupTemplate>
<tr id="itemPlaceholderContainer" runat="server">
<td id="itemPlaceholder" runat="server"></td>
</tr>
</GroupTemplate>
<ItemTemplate>
<td runat="server">
<table>
<tr>
<td>
<a href="NewsDetails.aspx?newsID=<%#:Item.NewsID%>">
<img src="/Catalog/Images/Thumbs/<%#:Item.ImagePath%>"
width="100" height="75" style="border: solid" /></a>
</td>
</tr>
<tr>
<td>
<a href="NewsDetails.aspx?newsID=<%#:Item.NewsID%>">
<p style="color: black;">
<%#:Item.NewsTitle%>
</p>
</a>
</td>
</tr>
<tr>
<td> </td>
</tr>
</table>
</p>
</td>
</ItemTemplate>
<LayoutTemplate>
<table style="width:100%;">
<tbody>
<tr>
<td>
<table id="groupPlaceholderContainer" runat="server" style="width:100%">
<tr id="groupPlaceholder"></tr>
</table>
</td>
</tr>
<tr>
<td></td>
</tr>
<tr></tr>
</tbody>
</table>
</LayoutTemplate>
</asp:ListView>
</div>
Behind the page:
public IQueryable<News> GetProducts()
{
var _db = new SiteStiri.Models.NewsContext();
IQueryable<News> query = _db.News;
if ("DesDate".Equals(DropDownSelect.SelectedItem.Value))
{
query = query.OrderByDescending(u => u.ReleaseDate);
}
if ("AsDate".Equals(DropDownSelect.SelectedItem.Value))
{
query = query.OrderBy(u => u.ReleaseDate);
}
if ("AsAlp".Equals(DropDownSelect.SelectedItem.Value))
{
query = query.OrderBy(u => u.NewsTitle);
}
if ("DesApl".Equals(DropDownSelect.SelectedItem.Value))
{
query = query.OrderByDescending(u => u.NewsTitle);
}
return query;
}
public void DropDownSelect_SelectedIndexChanged(object sender, EventArgs e)
{
GetProducts();
productList.DataBind();
}
How can i put here <a href="NewsDetails.aspx?newsID=<%#:Item.NewsID%>"> either the page link to my site if Link IS null or the Link of the link IS NOT null?

To give a more detailed answer, set the Link column as NOT NULL and set the default value to be your URL. This was, if the user / news editor doesn't enter a value, your URL will be added to the field. The advantage of this is that you don't need any code to check for NULL etc.
Also, make sure the UI validates the URL that's added with regular expression, in case a rogue value is added.
If you want to alter it in code, you could try something like this...
public class News
{
public string Title { get; set; }
public string Url { get; set; }
public IQueryable<News> GetNews()
{
var news = new List<News> {new News {Title = "News1", Url = "NewsURL"},
new News {Title = "News1"}};
return news.AsQueryable();
}
}
You could then take out the list with no links and update them with your link...
var news = new News();
var initialNews = news.GetNews();
var newsWithLink = initialNews.Where(n => n.Url != null);
var newsWithOutLink = initialNews.Where(n => n.Url == null);
foreach (var newsItem in newsWithOutLink)
{
newsItem.Url = "MyURL";
}
var newsToDisplay = newsWithLink.Concat(newsWithOutLink);
I've just put that small example together to show how to update the links.

Related

DataList button fires every time the page is refreshed

I have a link button in a DataList in a shopping cart that works fine. Once they have selected the product, if they refresh the page, it will retrigger this button.
<asp:DataList runat="server" ID="rpCategories" RepeatColumns="4" RepeatDirection="Horizontal" OnItemCommand="rpCategories_ItemCommand"
ItemStyle-HorizontalAlign="Center" ClientIDMode="Static" ItemStyle-CssClass="bigLink">
<ItemTemplate>
<table>
<tr>
<td>
<div class="<%=EnrollmentPacksBottomBox %>">
<div class="enrollment1ProImage">
<img src="../../Common/Images/products/large/<%# Eval("largeImages") %>" width="250" />
</div>
<div class="enrollment1ProductName">
<%# Eval("productName") %>
</div>
<div class="enrollment1DescriptionBottom1">
<%# Eval("description") %>
</div>
<div class="enrollment1Price">
<table>
<tr>
<td>
<%# String.Format(CultureInfo.GetCultureInfo(MyCulture), "{0:c}", Eval("price")) %>
</td>
<td>
<div class="enrollment1PvSpacer"></div>
</td>
<td>PV:
<%# Eval("pv") %>
</td>
</tr>
</table> <%-- new amount, and buttons- start--%>
<table class="cartButtonsHolder">
<tr>
<td>
<div class="">
<button type="button" style="border: none; background-color: white;">
<table class="cartButtons">
<tr>
<td rowspan="2">
<asp:TextBox runat="server" ID="quantityHolder" Text='<%# Eval("quantity") %>' CssClass="QuantityBox"/>
</td>
<td>
<asp:LinkButton runat="server" ID="upButton" OnClick="AddItem" CssClass="caretButton fas fa-caret-up" Text="" />
</td>
</tr>
<tr>
<td>
<asp:LinkButton runat="server" ID="downButton" OnClick="SubtractItem" CssClass="caretButton fas fa-caret-down fa-m" Text="" />
</td>
</tr>
</table>
</button>
</div>
</td>
<td>
<asp:LinkButton runat="server" OnClick="SelectPro1Bottom"><div class="enrollment1SelectButton"> Add to Cart</div></asp:LinkButton>
</td>
</tr>
</div>
</div>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
The code behind looks like this:
protected void SelectPro1Bottom(object sender, EventArgs e)
{
DAL oDal = new DAL();
var btn = (LinkButton)sender;
//var btn = (HtmlButton)sender;
var item = (DataListItem)btn.NamingContainer; //RepeaterItem
int index = item.ItemIndex;
int quantity = 0;
GetSelected(index);
Session["amount"] = 1;
//pull in the quantity
Quantities = Session["formatQuantities"] as List<int>;
List<OrderUserTypeHolder> TempHolder = new List<OrderUserTypeHolder>();
OrderUserTypeHolder oh = new OrderUserTypeHolder();
TempHolder = Session["userTypeHolder"] as List<OrderUserTypeHolder>;
int userType = 0;
int hasAutoship = 0;
string country = "";
userType = TempHolder[0].UserType;
hasAutoship = TempHolder[0].HasAutoship;
country = TempHolder[0].Country;
ProductIdList.Clear();
using (oDal)
{
//dist
if (userType == 2 && hasAutoship == 1)
{
SqlDataReader rd = oDal.ProductsGetAllByDescLengthAutoReader(country);
while (rd.Read())
{
ProductIdList.Add(Convert.ToInt32(rd["productId"]));
}
}
else if (userType == 2)
{
SqlDataReader rd = oDal.ProductsGetAllByDescLengthDistReader(country);
while (rd.Read())
{
ProductIdList.Add(Convert.ToInt32(rd["productId"]));
}
}
//pc
else if (userType == 3)
{
SqlDataReader rd = oDal.ProductsGetAllByDescLengthPcReader(country);
while (rd.Read())
{
ProductIdList.Add(Convert.ToInt32(rd["productId"]));
}
}
//retail
else
{
SqlDataReader rd = oDal.ProductsGetAllByDescLengthRetailReader(country);
while (rd.Read())
{
ProductIdList.Add(Convert.ToInt32(rd["productId"]));
}
}
oDal.Dispose();
}
//make sure we don't have an empty array
if (Quantities.Count > 0)
{
quantity = Quantities[index];
}
else
{
quantity = 1;
}
int productId = ProductIdList[index];
AddItemsToCart(productId, quantity, hasAutoship);
}
I have tried a wide variety of fixes including feeding a value of null to my datasource, changing my view state, and moving it inside !isPostback (the link button won't work). Every time you click the linkbutton it reloads the page (does not go in !isPostback) and refreshing the page has the same effect. Every time the page is rereshed, it will add another of the last item selected to the cart. I have tried everything I could think of and everything I have found online over the past several hours.
Any suggestions would be greatly appreciated!

Scheduler in asp.net to fetch data from website

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

How To use a html button to fire a c# function

I used a asp:button to bind the data from a textbox into a grid, but my problem was getting the page to stop refreshing. So I changed the asp:button to html button, because it was server side causing the page to refresh. Now I dont know how to use the same c# code to bind the data using html button.
Here's an example of my c# code:
//Site Class
class Sites
{
//Strings and variables are created based off text box Id to make matter easier to read
public string SiteName { get; set; }
public string Slick { get; set; }
public string UserID { get; set; }
}
//Created a new list based on class.
//Items are added based on whats in the textboxes
//and events are fired to gridview by the click of the class button
protected void SiteDetails_Click(object sender, EventArgs e)
{
List<Sites> list;
if (Session["list"] == null)
{
list = new List<Sites>();
}
else
{
list = (List<Sites>)Session["list"];
}
list.Add(new Sites() { SiteName = Sname.Text, Slick = Slick.Text, UserID = User_ID.Text });
Session["list"] = list;
SiteGrid.DataSource = list;
SiteGrid.DataBind();
}
And This is my Html aspx page:
Site Details
SiteName:
<td style="width: 102px; height: 8px;">Slic:</td>
<td style="width: 153px; height: 8px;">
<asp:TextBox ID="Slick" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 129px; margin-left: 40px; height: 23px;">User ID:</td>
<td style="width: 152px; height: 23px;">
<asp:TextBox ID="User_ID" runat="server" style="font-weight: bold"></asp:TextBox>
</td>
<td style="width: 102px; height: 23px;">
Password:</td>
<td style="width: 153px; height: 23px;">
<asp:TextBox ID="Pass" runat="server" TextMode="Password" ></asp:TextBox>
</td>
</tr>
<%-- //Site Button--%>
<tr>
<td></td>
<td>
<button ID="SiteDetails" OnClick="SiteDetails_Click()">AddSites</button>
</td>
</tr>
</table>
<%-- //Site GridView--%>
<asp:GridView ID="SiteGrid" class="table-bordered table-hover tableGridLines="None">
</asp:GridView>

c# postback dropdownlist always choose first value

I want to insert the selected item of drop down list into database but my drop down list keep returns the first option . auto post back is false .
codes here :
dropTask() = drop down list where I populate it from database.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dropTask();
}
}
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
String pathdirectory = (dropListActivity.SelectedItem.Text+"/");
String filepathImage = (pathdirectory + e.FileName);
EnsureDirectoriesExist(pathdirectory);
AjaxFileUpload1.SaveAs(Server.MapPath(filepathImage));
Session["filepathImage"] = filepathImage;
}
i had checked the value return from drop down list using label :
protected void btnDone_Click(object sender, EventArgs e)
{
if (Session["filepathImage"] != null)
{
string filepathImage = Session["filepathImage"] as string;
Label1.Text = filepathImage;
}
}
the label text show the first option of the drop down list value instead of the choice I have chosen . Please enlighten me on this .
ASPX:
<tr>
<td>
<h2>Upload your Story!</h2>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
</td>
</tr>
<tr>
<td colspan = "2"></td>
</tr>
<tr>
<td>
<b>Select Activity:</b>
</td>
<td>
<asp:DropDownList ID="dropListActivity" runat="server"
onselectedindexchanged="dropListActivity_SelectedIndexChanged">
</asp:DropDownList>
</td>
</tr>
<tr>
<td colspan = "2"></td>
</tr>
<tr>
<td>
<b>Story Title:</b>
</td>
<td>
<asp:TextBox ID="txtStoryTitle" runat="server"
ontextchanged="txtTitle_TextChanged" AutoPostBack="True"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
<b>Upload your files here:</b><br />
Multiple Images and 1 Audio file only.
</td>
<td class="style1">
<asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
onuploadcomplete="AjaxFileUpload1_UploadComplete"
/>
</td>
</tr>
<tr>
<td colspan = "2"></td>
</tr>
<tr>
<td>
<asp:Label ID="Label1" runat="server" ></asp:Label>
</td>
<td>
<asp:Button ID="btnDone" runat="server" Text="Done" onclick="btnDone_Click" />
</td>
</tr>
DropListActivity.SelectedItem.ToString should do the trick. There are a few other things you should keep in mind:
Make sure you are not populating the dropdownlist on a postback.
Selected value will only be available at the sever if the portion of
the page containing the dropdownlist control is posted back.i.e if
you are using an update panel your dropdownlist should be present
within that panel or if you are posting back the entire page then there wont be any problem at all provided you meet the first criteria.
Your event handler dropListActivity_SelectedIndexChanged will
always be fired when a page is posted back and the seleceted index
has changed. The event handler dropListActivity_SelectedIndexChanged will be called after the page_load subroutine is executed.
I assume you need something like:
private void SaveSelected()
{
ViewState["SelectedItem"] = dropListActivity.SelectedItem;
}
which you use on dropListActivity_SelectedIndexChanged and
private void LoadSelected()
{
if (ViewState["SelectedItem"] != null)
dropListActivity.SelectedItem = (ListItem)ViewState["SelectedItem"];
}
which you call after dropTask();
Please, refer to this post's answer
in dropListActivity_SelectedIndexChanged event do like
if(dropListActivity.Items.Count > 0)
{
ViewState["DropDownSelectedValue"] = dropListActivity.Item.SelectedValue;
}
and on Load or databind of drop down list event write
if(ViewState["DropDownSelectedValue"] != null && dropListActivity.Items.Count > 0)
{
dropListActivity.SelectedValue = ViewState["DropDownSelectedValue"].ToString();
}

ASP.net - Unsure on how to generate table

Given the following HTML:
<asp:content id="Content1" contentplaceholderid="mainContent" runat="server">
<div class="scrollRow">
<table width="100%">
<tr>
<td width="25%">Site name: <b>My site</b></td>
<td>Created on 12th Aug 2010</td>
<td align="right"><button onclick="doRevert(1)">Revert to this</button></td>
</tr>
</table>
</div>
<div class="scrollRow">
<table width="100%">
<tr>
<td width="25%">Site name: <b>Another site</b></td>
<td>Created on 3rd Aug 2010</td>
<td align="right"><button onclick="doRevert(1)">Revert to this</button></td>
</tr>
</table>
</div>
<div class="scrollRow scrollRowOn">
<table width="100%">
<tr>
<td width="25%">Site name: <b>Another site</b></td>
<td>Created on 3rd Aug 2010</td>
<td align="right"></td>
</tr>
</table>
</div>
</asp:content>
Which is a list of rows, how am I programatically meant to generate these after I have retrieved the SQL rows from the code behind? Do I need to make my own control, or something along those lines?
Try something along these lines:
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_OnItemDataBound">
<ItemTemplate>
<div class='<%# SetClass(Eval("SiteId")) %>'>
<table width="100%">
<tr>
<td width="25%">Site name: <b><%# Eval("SiteName") %></b></td>
<td>Created on <%# DataBinder.Eval(Container.DataItem, "CreateDate", "{0:dd MMM yyyy}")%></td>
<td align="right"><button id="btnRevert" runat="server" onclick="doRevert(1)">Revert to this</button></td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:Repeater>
In the codebehind Repeater1_OnItemDataBound event you could set the button to be visible or not, depending on whether the item is the current one.
protected void Repeater1_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
RepeaterItem item = e.Item;
if (item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.Item)
{
Site site = e.Item.DataItem as Site; //List<Site> is what you are binding to the repeater
if (site.SiteId == currentSiteId)
{
var btn = e.Item.FindControl("btnRevert") as Button;
if (btn != null)
{
btn.Visible = false;
}
}
}
}
CSS Classes for your items can be set like this:
protected string SetClass(object obj) {
int siteId;
if (int.TryParse(obj.ToString(), out siteId)){
if (siteId == currentSiteId) //currentSiteId determined elsewhere
{
return "scrollRow";
}
}
return "scrollRow scrollRowOn";
}
There are a lot of ways to get to this, of course, but here's one (possibly not the best, but that's subjective anyway):
Assuming C# web forms and ADO.Net, and assuming you need precisely that html, you could loop over the rows in the DataSet and output the html.
DataSet ds = {data set from your sql}
StringBuilder html = new StringBuilder();
foreach (DataRow row in DataSet.Tables[0].Rows) {
html.Append( string.Format(#"<div class=""scrollRow"">
<table width=""100%"">
<tr>
<td width=""25%"">Site name: <b>{0}</b></td>
<td>Created on {1}</td>
<td align="right"><button onclick="doRevert(1)">Revert to this</button></td>
</tr>
</table>",row["sitename"], row["createdate"]));
}
You could include the html by having an <asp:Literal> in the page code and setting the Text property.
You could also do it by creating System.Web.UI.WebControls.Table nodes in the code behind and adding TableRows and TableCells to them, using the same loop, and then adding those to the page using. Given what you've given us thus far, you seem to be adding controls to a page with a MasterPage, so you would need to add your tables to the Master's ContentPlaceHolder, which you can find and add controls to like so:
ContentPlaceHolder ph = (ContentPlaceHolder)this.Master.FindControl( "ContentPlaceHolder1" );
foreach (DataRow row in DataSet.Tables[0].Rows) {
Panel pnl = new Panel();
Table tbl = new Table();
TableRow tblrow = new TableRow();
TableCell cell1 = new TableCell();
cell1.Text = string.Format("Site name: <b>{0}</b>",row["sitename"]);
row.Cells.Add(cell1);
tbl.Rows.Add(tblrow);
pnl.Controls.Add(tbl);
ph.Controls.Add(pnl);
}
You can set properties on the TableRows and TableCells, but if you do it this way you will lose some control over the html that's generated, most notably the html ID attributes. You don't seem to be using those, so perhaps that's ok.
I would suggest the repeater control. You can use it something like this:
<asp:Repeater runat="server" id="myRepeater">
<ItemTemplate>
<div class="scrollRow scrollRowOn">
<table width="100%">
<tr>
<td width="25%">Site name: <b><% Eval("SiteName")%></b></td>
<td>Created on <% Eval("CreatedOn")%></td>
<td align="right"></td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:Repeater>
Then you need to bind your data to it in the Page_Load event:
myRepeater.DataSource = myData;
myRepeater.DataBind();
Where my data is the data that you retrieve from the database.

Categories

Resources