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

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>

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

Checking a query Result in ASP

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.

ASP.NET Paging next page button does not work properly

I'am trying to divide all of my products that i listed by using a repeater to pages. For example there are 3 pages. The paging looks well but when i click to next page button it is going to page 4 which is not exist actually. What can be the reason ? Implementation is below.
private void showShoes()
{
dataInThePage = new PagedDataSource()
{
DataSource = ap.getShoes(),
AllowPaging = true,
PageSize = 2,
CurrentPageIndex = pageNo
};
shoeRepeater.DataSource = dataInThePage;
shoeRepeater.DataBind();
pageAmount = dataInThePage.PageCount - 1;
//
pageInfoLabel.Text = "Page: " + (dataInThePage.CurrentPageIndex + 1) + "/" + dataInThePage.PageCount + " - Number of Shoes: " + (dataInThePage.DataSourceCount);
//
previousButton.Enabled = !dataInThePage.IsFirstPage;
nextButton.Enabled = !dataInThePage.IsLastPage;
}
private int pageNo
{
get
{
if (ViewState["pageNumber"] != null)
return Convert.ToInt32(ViewState["pageNumber"]);
return 0;
}
set
{
ViewState["pageNumber"] = value;
}
}
private int pageAmount
{
get
{
if (ViewState["pageNumber"] != null)
return Convert.ToInt32(ViewState["pageNumber"]);
return 0;
}
set { ViewState["pageNumber"] = value; }
}
public PagedDataSource dataInThePage { get; set; }
protected void previousButton_Click(object sender, EventArgs e)
{
pageNo -= 1;
showShoes();
}
protected void nextButton_Click(object sender, EventArgs e)
{
pageNo += 1;
showShoes();
}
Front-end:
<ajaxToolkit:TabPanel ID="TabPanel5" runat="server">
<HeaderTemplate>Show Shoes</HeaderTemplate>
<ContentTemplate runat="server">
<asp:Repeater ID="shoeRepeater" runat="server">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<table border="1" style="border-color:#ff9900; width:400px; font-weight:bold; font-family:'Oswald', Arial, sans-serif;">
<tr>
<td rowspan="6" style="width:150px; height:150px;">
<image src="shoeImages/<%#DataBinder.Eval(Container.DataItem,"ImagePath") %>"></image>
</td>
</tr>
<tr>
<td>
<%#DataBinder.Eval(Container.DataItem,"BrandName") %> - <%#DataBinder.Eval(Container.DataItem,"ModelName") %>
</td>
</tr>
<tr>
<td>
Price: $<%#DataBinder.Eval(Container.DataItem,"Price") %>
</td>
</tr>
<tr>
<td>
Size: <%#DataBinder.Eval(Container.DataItem,"Size") %>
</td>
</tr>
<tr>
<td>
Color: <%#DataBinder.Eval(Container.DataItem,"PrimaryColor") %> - <%#DataBinder.Eval(Container.DataItem,"SecondaryColor") %>
</td>
</tr>
<tr>
<td>
Quantity: <%#DataBinder.Eval(Container.DataItem,"Quantity") %>
</td>
</tr>
</table>
</ItemTemplate>
<FooterTemplate></FooterTemplate>
</asp:Repeater>
<div style="width:600px; height:20px;">
<div style="width:50px; height:100%; float:left">
<asp:Button ID="previousButton" runat="server" OnClick="previousButton_Click" Text="<<" Width="50px"/>
</div>
<div style="width:500px; height:100%; float:left; text-align:center">
<asp:Label ID="pageInfoLabel" runat="server" Text=" "></asp:Label>
</div>
<div style="width:50px; height:100%; float:left">
<asp:Button ID="nextButton" runat="server" OnClick="nextButton_Click" Text=">>" Width="50px"/>
</div>
</div>
</ContentTemplate>
</ajaxToolkit:TabPanel>
I had to guess on a number of things, but I was able to take the posted code and get it to work in VS 2010 using an ASP.NET 4.0 project.
Here are the things I did to get it working:
Add a Shoe POCO with the 8 public properties referenced in the .aspx page (not shown)
Add a FakeShoeRepository class that has a private static List<Shoe> with 9 shoes (not shown)
Add a static method called getShoes() that returns a reference to the private member variable of the repository (not shown)
Set the dataInThePage.DataSource = FakeShoeRepository.getShoes() (not shown)
Add a Page_Load() event
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
pageNo = 0;
showShoes();
}
}
Remove the pageAmount property
Remove the one place pageAmount was being set in the showShoes() method (this was effectively setting ViewState["pageNumber"] = PageCount - 1)
The last two items are where the actual problem was in the provided code.

reference textbox in user control from inside the same control

I have a user control with a text box and a button. When I press the button, I try to read the contents using the text box's ID (from the user control's code behind) but I always get a blank result. What is the proper way to reference a control in a user control from the same user control.
I read elsewhere that I should simply use the control ID, but somehow it is not working. I must be doing something wrong and I am hoping this is a common mistake and that someone can she some light on this.
Edit:
Markup:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ForumPostControl.ascx.cs" Inherits="ForumPostControl" debug="true" %>
<div id="PostDiv" runat="server">
<table width="100%" cellpadding="0" cellspacing="0" border="0" style="border:1px solid white; border-radius:5px; margin-bottom:5px;">
<tr>
<td valign="top" width="52" style="text-align:center; padding:10px 0px 10px 0px; border-bottom:1px dashed #FFF;">
<asp:Image ID="imgReplyPoster" runat="server" />
</td>
<td valign="middle" style="text-align:left; padding:10px 0px 10px 0px; border-bottom:1px dashed #FFF;">
<asp:HyperLink ID="lnkReplyPoster" runat="server">lnkReplyPoster</asp:HyperLink><br />
<asp:Label ID="lblCreated" runat="server" Text="Label"></asp:Label>
</td>
<td style="text-align:right; padding:10px 20px 10px 0px; border-bottom:1px dashed #FFF;">
<asp:LinkButton ID="btnReply" runat="server" onclick="btnReply_Click">Reply</asp:LinkButton>
<asp:LinkButton ID="btnDelete" runat="server" OnClick="btnDelete_Click" OnClientClick="return ConfirmClick('Do you really want to delete this post?');"><img src="images/icons/trash16.png" alt="Delete" border="0" /></asp:LinkButton>
</td>
</tr>
<tr>
<td valign="top" align="justify" style="padding:10px;" colspan="3">
<asp:Literal ID="ltrlPostBody" runat="server"></asp:Literal>
</td>
</tr>
</table>
<asp:PlaceHolder ID="phReply" runat="server" Visible="False">
<div align="center" style="padding:5px 10px 10px 10px;">
<asp:HiddenField ID="hdnParentID" runat="server" />
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td>
<asp:TextBox ID="txtReply" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right" style="padding-top:20px;">
<asp:LinkButton ID="lnkPostReply" runat="server" OnClick="lnkPostReply_Click">Post reply</asp:LinkButton>
</td>
</tr>
</table>
</div>
</asp:PlaceHolder>
</div>
Code behind for saving text to database:
protected void lnkPostReply_Click(Object sender, EventArgs e)
{
String connectionString = (String)System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
SqlConnection cnn = new SqlConnection(connectionString);
SqlCommand cmd;
String strSQL;
cnn.Open();
strSQL = "INSERT INTO ForumThreads (ForumID, ParentID, PostBody, Created, CreatedBy, Modified, ModifiedBy) VALUES " +
"(#ForumID, #ParentID, #PostBody, GETDATE(), #CreatedBy, GETDATE(), #CreatedBy);";
cmd = new SqlCommand(strSQL, cnn);
cmd.Parameters.AddWithValue("#ForumID", prvForumID);
cmd.Parameters.AddWithValue("#ParentID", prvForumThreadID);
cmd.Parameters.AddWithValue("#PostBody", txtReply.Text);
cmd.Parameters.AddWithValue("#CreatedBy", CurrentMember.MemberID);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Close();
cnn.Dispose();
Response.Redirect("forum_topic.aspx?TID=" + prvEncryptedTID);
}
The problem is with reading the txtReply control.
Edit #2
I am still struggling with this and experimenting stuff. Here are some finding, I hope they can help solve the mystery. I noticed that I can read properties from the text box control such as width and ID but I cannot read the text that is entered by the user. It always returns blank. If I pre set the text programmatically to, say, "Initial Text", then when I try to read the .text property, I still get "Initial Text", no matter what the user enters. It is as if the text typed the user is lost on post back.
As you mentioned that you are using the usercontrol inside a repeater, I would check the page's Page_Load event method to see I am not rebinding the repeater at postback:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Repeater1.DataSource = GetData();
Repeater1.DataBind();
}
}
And my Repeater1_ItemDataBound may look something like:
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
ForumPostControl myControl = (ForumPostControl)e.Item.FindControl("ForumPostControl1");
myControl.MyProperty = 20;//My custom property of user control
}
}
Now, each postback may wipe out my usercontrol's custom property. I need to make sure it persist on postback. In my ForumPostControl.ascx.cs I would store the value of this property in visestate and retrieve when needed. I should have this code in my usercontrol:
public int MyProperty
{
get
{
int myProperty = 0;
if (ViewState["MyProperty"] != null)
{
int.TryParse(ViewState["MyProperty"].ToString(), out myProperty);
}
return myProperty;
}
set
{
ViewState["MyProperty"] = value;
}
}

Categories

Resources