ASP.NET Datalist calculate field - asp.net

I recently decided to implement tax on an ecommerce website I've built for fun more than anything and I've hit a stumbling block.
My implementation works well, tax is applied correctly etc, however a buddy pointed out to me today that prices on product pages are normally displayed inc tax.
I was thinking, rather than editing the Business and Data tier, I could change this on the DataList itself but I can't for the life of me work out how I'd actually do that. I've had a look in some text books and had a search around online but because I don't actually know what I'm looking for, I'm stuck :(.
Datalist:
<asp:DataList ID="list" runat="server" RepeatColumns="2" CssClass="ProductList" RepeatDirection="Horizontal"
Width="542px" EnableViewState="False" onitemcommand="list_ItemCommand">
<ItemTemplate>
<div style="width:271px;">
<h3 class="ProductName"><%# HttpUtility.HtmlEncode(Eval("Name").ToString()) %></h3>
<img width="100" border="0" src="<%# Link.ToProductImage(Eval("Thumbnail").ToString()) %>" alt='<%# HttpUtility.HtmlEncode(Eval("Name").ToString()) %>' />
<%# HttpUtility.HtmlEncode(Eval("Description").ToString()) %>
<p>
<b>Price:</b>
<%# Eval("Price", "{0:c}") %>
</p>
<p>
<asp:Button ID="addToCartButton" runat="server" Text="Add to Basket" CommandArgument='<%# Eval("ProductID") %>' CssClass="SmallButtonText" />
</p>
</div>
</ItemTemplate>
</asp:DataList>
Code behind:
// Retrieve the list of products in a Sub Category
list.DataSource = CatalogAccess.GetProductsInSubCategory(subCategoryId, page, out howManyPages);
list.DataBind();
E.g. if the price in the DB is £5, I'd need it to be displayed in the datalist above as £6 which includes the current UK VAT rate of 20%.
So:
DBPrice * 1.2 = IncVatPrice
I hope this makes sense!
Thanks in advance,
Matt

Instead of
<%# Eval("Price", "{0:c}") %>
use an expression somewhat similar to
<%# String.Format("{0:c}", (Decimal)Eval("Price")*1.2) %>
Or implement a function in codebehind:
protected string IncludeVat(object dataItem)
{
Decimal price = (Decimal)DataBinder.Eval(dataItem, "Price");
return String.Format("{0:c}", price * 1.2);
}
and call it in your DataList like that
<%# IncludeVat(Container.DataItem) %>
http://www.pluralsight-training.net/community/blogs/fritz/archive/2005/12/16/17507.aspx

Related

ASP.NET Linkbutton not getting dynamic value for commandargument value

<%
foreach (training t in traininglist)
{
%>
<tr>
<td><%=t.TrainingId%></td>
<td><%=t.TrainingName%></td>
<td>
<asp:LinkButton runat="server" ID="EditBtn"
Text="Edit" OnCommand="editbtn_OnCommand"
CommandArgument='<%# t.TrainingId %>' CommandName="edit" />
</td>
</tr>
<% } %>
where,
training is the class and traininglist is List<training> defined in Page_Load() function in codebehind.
I am trying to call the
public void editbtn_OnCommand(object sender, CommandEventArgs e)
{
String myeid = e.CommandArgument.ToString();
....
}
Here, myeid is not getting value but always shows <%# t.TrainingId %>
i have already tried all other options like <%: t.TrainingId %> or <%=t.TrainingId %>
The output of Tag "<%= %>" is more likely similar to use Response.Write in your code. so these tags are used to display the value to the response object.
That's why,as per my understanding, You can't used these tags to set commandargument property of controls unless you are using DataBinding. If you are using DataBinding then these tags "<%= %>" are used to set the property of controls.
Because you are here looping through each item in list on html table, my suggestion is to use GridView or Repeater and then Bind through your List Object. if you are using this way, you can get rid of unwanted formatting issues of html tables also.
Refer http://msdn.microsoft.com/en-us/library/6dwsdcf5(VS.71).aspx
If you want to use repeater then you can use these specific tags, and this should be your code(not actual code, just sample one)
<asp:Repeater id="myRepeater" runat="server" >
<ItemTemplate>
<div>
<asp:LinkButton runat="server" id="EditBtn" CommandName="edit"
CommandArgument="<%#Container.DataItem.TrainingId %>" Text="Edit"
OnCommand="editbtn_OnCommand" />
</div>
</ItemTemplate>
</asp:Repeater>

How to make this data control reusable for different content and data?

I'm using ASP.NET Web Forms, and I've got a Repeater control to display some data. Currently it looks like this:
<asp:Repeater runat="server" ID="blah" OnItemDataBound="blah" OnItemCommand="blah">
<HeaderTemplate>
<ul class="itemList">
</HeaderTemplate>
<ItemTemplate>
<li runat="server" id="listItem" class="itemNormal" onmouseover="this.className = 'itemHover';" onmouseout="this.className = 'itemNormal';">
<asp:LinkButton runat="server" ID="btn_select" CommandName="Select" Text="Select" style="display: none;"></asp:LinkButton>
<strong>Date/Time:</strong> <%# DataBinder.Eval(Container.DataItem, "date") %><br />
<strong>Details:</strong> <%# DataBinder.Eval(Container.DataItem, "details") %><br />
<strong>Status:</strong> <%# DataBinder.Eval(Container.DataItem, "status") %><br />
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
This list has hover behaviour, etc. and I'd like to reuse the same style of list across my project, just with different data (really just replacing the three lines with <strong> tags in). However, I obviously don't want to copypaste and change it every time it's used, so I thought I'd try and make it into a User Control:
<asp:Repeater runat="server" ID="blah" OnItemDataBound="blah" OnItemCommand="blah">
<HeaderTemplate>
<ul class="itemList">
</HeaderTemplate>
<ItemTemplate>
<li runat="server" id="listItem" class="itemNormal" onmouseover="this.className = 'itemHover';" onmouseout="this.className = 'itemNormal';">
<asp:LinkButton runat="server" ID="btn_select" CommandName="Select" Text="Select" style="display: none;"></asp:LinkButton>
<%= DataString %>
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
And in my corresponding class in CodeBehind:
public string DataString { get; set; }
So my main aim was to do this:
<uc:MyUserControl runat="server" ID="blah" DataString="<strong>Date/Time:</strong><%# DataBinder.Eval(Container.DataItem, "date") %> ETC..." />
But it seemed that ASP.NET wanted to evaluate the <% %> in the string there and then, and I tried different ways to get around it such as this:
<% string theDataString = "<strong>Date/Time:</strong> <%# DataBinder.Eval(Container.DataItem, "date") %>"; %>
<uc:MyUserControl runat="server" ID="blah" DataString='<%= theDataString %>' />
But I ran into trouble again with the closing %> in theDataString, and even after replacing it with something like {0: %} (to escape the % sign: can't remember the exact syntax), which did escape it correctly, I discovered that you can't actually use the <%= %> inside an attribute, which was annoying.
My last-ditch attempt was to set DataString in my page's CodeBehind, and the HTML <strong> rendered correctly, but ASP.NET didn't evaluate the <%# %> and just spat it out literally. So I'm kind of stuck as I can't think of anything else... (by the way I'm still relatively new to ASP.NET)
I'm not even sure this is a good way to go about it - previously I thought about making it into a templated user control but this method seemed simpler and it was something I already knew how to do, or so I thought. So any help with this would be greatly appreciated, thanks!
EDIT: Just to be clear, my emphasis here is on the re-usability of this particular control - so I will be able to display different types of data records in this style of list (clickable, highlight behaviour etc).
If your goal is to have three lines appear as bold instead of normal text, then your best bet is to use something more geared towards website-display than something programmatic and heavy-handed like a dynamic server-side user control. For example:
<asp:Repeater runat="server" ID="blah" OnItemDataBound="blah" OnItemCommand="blah">
<HeaderTemplate>
<ul class="itemList">
</HeaderTemplate>
<ItemTemplate>
<li runat="server" id="listItem" class="itemNormal" onmouseover="this.className = 'itemHover';" onmouseout="this.className = 'itemNormal';">
<asp:LinkButton runat="server" ID="btn_select" CommandName="Select" Text="Select" style="display: none;"></asp:LinkButton>
<span class="displayMode">Date/Time:</span> <%# DataBinder.Eval(Container.DataItem, "date") %><br />
<span class="displayMode">Details:</span> <%# DataBinder.Eval(Container.DataItem, "details") %><br />
<span class="displayMode">Status:</span> <%# DataBinder.Eval(Container.DataItem, "status") %><br />
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
And then, programmtically show:
<style type="text/css">
.displayMode { font-weight: bold; }
/* and/or */
.displayMode { text-decoration: underline; }
</style>
Use the right tool for the job, in this case, I don't feel as though server-side code is the right way to accomplish this task. If, on the other hand, you need to change the content of the insides of your <li> tags, then yes you would have to do it in C#. However, if that were the case you could easily bind it to a different object or use a different control or inherit the control or any number of other methods. For your specific case, just use standard HTML manipulation techniques.

Repeater ItemCommand doesn't work when linked to the page

EDIT: I've found what's causing the issue, but I don't know why and I don't know how to fix it. I'm using JQuery Mobile to theme my site and when I remove this line:
<div data-role="page" data-theme="a">
I can get the repeater to work properly. Does anyone know how I can keep my theme and get this repeater to work?
Alright I have a repeater like this:
<asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand" EnableViewState="true">
<ItemTemplate>
<li>
<asp:LinkButton ID="Button1" runat="server" Text='<%# Container.DataItem %>' CommandName="Redirect" />
</li>
</ItemTemplate>
</asp:Repeater>
And the code behind it looks like this
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Redirect")
{
Session["contact"] = ((LinkButton)e.CommandSource).Text;
Response.Redirect("Contact_Details.aspx");
}
}
And if I navigate directly to this page (without being linked to it from another page) the repeater will fire the ItemCommand. But, if I have my login page redirect back to this page or just click on a link to this page from another page, the itemcommand is never triggered when clicking on the link buttons. Any clues as to why this is?
EDIT: The full code for this page is:
<%# Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="Contacts.aspx.cs" Inherits="WebApplication3.Contacts" %>
<%# MasterType VirtualPath = "~/Site1.Master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand" EnableViewState="true">
<HeaderTemplate> <ul data-role='listview' data-theme='c' data-inset='true'>
<li data-role="list-divider"><center><h1>Contacts</h1></center></li></HeaderTemplate>
<ItemTemplate>
<li>
<asp:LinkButton ID="Button1" runat="server" Text='<%# Container.DataItem %>' CommandName="Redirect" />
</li>
</ItemTemplate>
<FooterTemplate></ul></FooterTemplate>
</asp:Repeater>
</asp:Content>
In page load I connect to a webservice that connects to exchange and returns an array out. I do a quick array conversion to an arraylist then the rest of the code is:
//Converts the array grabbed from the webservice to an arraylist
ArrayList testList = ArrayList.Adapter(contactsList);
Repeater1.DataSource = testList;
Repeater1.DataBind();
Repeater1.ItemCommand += new RepeaterCommandEventHandler(Repeater1_ItemCommand);
}
So I figured out the line that was giving me an issue.
In my master page I had:
<div data-role="page" data-theme="a">
This line is for my JQuery Mobile Theme. When I commented it out, it broke the theme but the repeater worked. So I took a look into the JQuery Mobile docs and found that I could put rel="external" as an attribute to the link that links to this page. This removes the AJAX transitions and forces the page to refresh when clicked.
Not sure exactly why this was an issue, any gurus have an idea?

How to prevent ItemTemplate and AlternatingItemTemplate from creating newlines

In aspx, using either a ListView, Repeater, or any of the other standard controls that are listed under the visual studio 2010 data toolbox: My data source is simply a set of records made up of ID, title, first_name, last_name, degree. I am trying to print them on a single line (going to a newline when the end of a line is reached, not necessarily by a new record), however, the ItemTemplate and AlternatingItemTemplate seems to print each record as a newline. Is there a way to get rid of that automatic newline? (I tried ItemSeparatorTemplate, but that didn't work)
I don't think that it is necessary, but I figured that I'll just give you the code:
<asp:ListView ID="ListView2" runat="server" DataSourceID="AccessDataSource2">
<ItemTemplate>
<a href='#<%# Eval("ID") %>' /><%# Eval("title")%> <%# Eval("first_name")%> <%# Eval("last_name")%> <%# Eval("degree")%></a>
</ItemTemplate>
<AlternatingItemTemplate>
<a href='#<%# Eval("ID") %>' /><%# Eval("title")%> <%# Eval("first_name")%> <%# Eval("last_name")%> <%# Eval("degree")%></a>
</AlternatingItemTemplate>
</asp:ListView>
Use Datalaist and make RepeatDirection="Horizontal".
<asp:DataList ID="datalist1" runat="server" RepeatDirection="Horizontal"></asp:DataList>

How to make UpdatePanel inside ListView work?

I have a page with a listview that shows something like posts. On each post there should be a "rate box" which works similar to the "Like" button in facebook. The rate box is a User Control, that has an update panel inside it.
If I put the control with some random values in the page it works great - but when I put it inside the ListView, where it should be located, it won't work. The method is being called, but nothing happens.
I simplified the code a bit to make it easier to understand:
The "rate box" control:
protected void OnRateClick(object sender, ImageClickEventArgs e)
{
Rate++;
RateAmountLiteral.Text = Rate.ToString();
RateButton.Visible = false;
FeedbackLiteral.Visible = true;
rateButtonPanel.Update();
}
ascx:
<div class="rate_div">
<asp:UpdatePanel ID="rateButtonPanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<fieldset>
Rate:
<asp:Literal ID="RateAmountLiteral" runat="server"></asp:Literal>
<asp:ImageButton ID="RateButton" runat="server" ImageUrl="icn_rate.png"
OnClick="OnRateClick" />
<asp:Literal ID="FeedbackLiteral" runat="server" Visible="false">Thanks for rating!</asp:Literal>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
</div>
aspx (using the control):
<asp:ListView ID="PostsView" runat="server" ItemPlaceholderID="itemPlaceHolder2"
<LayoutTemplate>
<div class="posts_div">
<asp:PlaceHolder ID="itemPlaceHolder2" runat="server" />
</div>
</LayoutTemplate>
<ItemTemplate>
<div class="post_div">
<div class="post_body">
<%# CurrentPost.Body %>
</div>
<UC:RatingBox id="RatingBox" runat="server"
PostID="<%# CurrentPost.ID %>"
Rate="<%# CurrentPost.Rate %>"/>
By: <a href="<%# CurrentPost.Author.LinkToProfile %>">
<%# CurrentPost.Author.DisplayName %>
</a> |
<%# CurrentPost.LiteralTime %>
</div>
</ItemTemplate>
</asp:ListView>
While debugging I noticed the controls in the method "OnRateClick" are empty and don't contain the right values. Please advice.
Also if you have any comments about the way I did things, don't hold yourself.
Thanks
There are a lot things that you may not have set up, I cannot tell from just the code snippet you have given. But make sure you do the following: -
1) Place a ScriptManager "" on the page.
If you are using master page in your application and your web page uses the master page, place script manager in master page. Or alternatively,you can also place script manager on specific web pages anyway.
2) Add a Triggers for the button RateButton in your Update panel.

Resources