Search Results

Search found 4215 results on 169 pages for 'andrew price'.

Page 14/169 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • php in_array() inside a foreach

    - by 432skronker
    I am having issues with using in_array() inside a foreach loop. Not sure if this is even possible or if I am doing something ridiculous where there are better ways. What I want to do is go through all the items and if their item id matches one thats in the array, return true and add the price of the item to a runninng total. $price = 0; $result = false; $array = array(1533, 2343, 2333); foreach($order['items'] as $item){ if(in_array($item['Item'], $array)){ $result = true; $price += $item['Price']; } } **UPDATED** Here is the order array [items] => Array ( [0] => Array ( [Item] => 139957 [OrderID] => 16025 [SizeID] => 24 [Price] => 46.00 ) [1] => Array ( [Item] => 2343 [OrderID] => 16025 [SizeID] => 12 [Price] => 32.00 ) ) [data] => Array ( )

    Read the article

  • Community Megaphone Podcast

    - by Steve Michelotti
    Last week I had the pleasure of being a guest on the Community Megaphone Podcast with Andrew Duthie and Dane Morgridge. We discussed .NET 4, C# 4, MVC 2, “geek religious wars”, and of course community. You can check out Show #5 here or directly download it. Thanks to Dane and Andrew for having me on the show!

    Read the article

  • SOA &amp; E2.0 Partner Community Forum XIII registration is open

    - by Jürgen Kress
    INVITATION TO THE ORACLE SOA AND E2.0 PARTNER COMMUNITY FORUM Do you want to learn about how to sell the value of Fusion Middleware by combining SOA and E2.0 Solutions? We would like to invite you to become updated and trained at our SOA and E2.0 Partner Community Forum March on 15th and 16th 2011 in Utrecht, The Netherlands. Keynote: Andrew Sutherland and Andrew Gilboy The Oracle SOA and E2.0 Partner Community Forum is a wonderful opportunity to: learn how to sell the value of Fusion Middleware bij combining SOA and E2.0 solutions meet with Oracle SOA and E2.0 Product management exchange knowledge learn from successful SOA, BPM, WebCenter and UCM implementations understand Oracle's Fusion Applications Strategy network within the Oracle SOA Partner Community and the Oracle E2.0 Partner Community During this highly informative event you can learn about partner success stories, participate in an array of break out sessions, exchange information with other partners and enjoy a vibrant panel discussion. Additionally to the SOA and E2.0 Partner Community Forum, you can participate in technical hands on workshops on March 17th and 18th. The goal of these workshops is to prepare you for customer implementations. Places are limited, so don't delay and register now by clicking here. Registration takes a few minutes and is free of charge, except in case of cancellation or no show (cancellation fee € 150). For more information, please visit our website. Best regards Jürgen Kress & Hans Blaas SOA & E2.0 Partner Adoption EMEA Agenda March 15th 2011 Welcome & Introduction Keynote Oracle Middleware Strategy and information on Application Grid and Exalogic Andrew Sutherland, SVP Middleware Sales EMEA, Oracle Keynote Managing Online Customer, Partner and Employee Engagement with Oracle E2.0 Solutions Andrew Gilboy, VP E2.0 Sales EMEA, Oracle Partner SOA/BPM Reference Case Partner WebCenter/UCM Reference Case SOA Suite PS3 David Shaffer, VP Product Management, Oracle Why Specialization is important for Partners Nick Kritikos, Hans Blaas & Jürgen Kress, Alliances & Channels, Oracle   Agenda March 16th 2011 Welcome & Introduction Day II Breakout round 1 - SOA Suite 11g PS3 & OSB - Importance of ADF & JDeveloper - SOA Security IDM - WebCenter PS3, Whats new - E2.0 Sales Plays Breakout round 2 - WebCenter PS3, Whats new - Application Management Enterprise manager and Amberpoint - ADF/WebCenter 11g integration with BPM Suite 11g - Importance of ADF & JDeveloper - JCAPS & OC4J migration opportunities for service business Breakout round 3 - BPM 11g: Whats new - Universal Content management 11g - SOA Security Management - E2.0 Surrounding Products: ATG, Documaker, Primavera - Middleware Industry Value Propositions & Sales Play Fusion Application SOA & E2.0 Summary & Closing For registration and additional information, please visit our website. For more information on SOA Specialization and the SOA Partner Community please feel free to register at www.oracle.com/goto/emea/soa (OPN account required) Blog Twitter LinkedIn Mix Forum Wiki Website Technorati Tags: SOA Community,SOA,SOA Partner Community Forum,SOA Community Forum,OPN,Jürgen Kress

    Read the article

  • bash command for each file in a folder

    - by Robert
    I have a set of files on which I would like to apply the same command and the output should contain the same name as the processed file but with a different extension. Currently I am doing rename /my/data/Andrew.doc to /my/data/Andrew.txt I would like to do this for all the .doc files from the /my/data/ folder and to preserve the name. I tried several versions but I guess I have something wrong in the syntax as I an new to linux.

    Read the article

  • With jQuery and I need help getting individual table row titles attributes from an xml file

    - by bfsarmi
    I'm usig tablesorter jQuery to parse this xml file <?xml version="1.0" encoding="iso-8859-1"?> <CATALOG> <CD> <TITLE>Title 01</TITLE> <ARTIST>Artist 01</ARTIST> <COUNTRY>Country 01</COUNTRY> <PRICE>10.00</PRICE> <YEAR>2010</YEAR> <INFO>Tooltip Info 01</INFO> </CD> <CD> <TITLE>Title 02</TITLE> <ARTIST>Artist 02</ARTIST> <COUNTRY>Country 02</COUNTRY> <PRICE>9.00</PRICE> <YEAR>2009</YEAR> <INFO>Tooltip Info 02</INFO> </CD> <CD> <TITLE>Title 03</TITLE> <ARTIST>Artist 03</ARTIST> <COUNTRY>Country 03/COUNTRY> <PRICE>8.00</PRICE> <YEAR>2008</YEAR> <INFO>Tooltip Info 03</INFO> </CD> </CATALOG> and with this code <script type="text/javascript"> $(document).ready(function(){ $.ajax({ type: "GET", url: "file.xml", dataType: "xml", success: function(xml){ $(xml).find("CD").each(function(){ $("#tablebody").append('<tr><td>' + $(this).find("TITLE").text() + '</td><td>'+ $(this).find("ARTIST").text() + '</td><td>'+ $(this).find("COUNTRY").text() + '</td><td>'+ $(this).find("PRICE").text() + '</td><td>'+ $(this).find("YEAR").text() + '</td></tr>'); }); } }); }); </script> I'm new at javascript and have been trying with no luck for a couple of hrs to get the text from the INFO/INFO tags in the xml file to show as title attributes for each table row. The reason for that is that I need to have individual popup tooltips on mouse-over each table row. Many Thanks in advance for any kind of help or suggestions!

    Read the article

  • JavaScript Coding for Finding Shipping Total

    - by user2913279
    I am having a very hard time with this code. I have been working on it for days and cannot seem to figure it out. Please help!! Here are the specific I need for the code: Many companies normally charge a shipping and handling charge for purchases. Create a Web page that allows a user to enter a purchase price into a text box and includes a JavaScript function that calculates shipping and handling. Add functionality to the script that adds a minimum shipping and handling charge of $1.50 for any purchase that is less than or equal to $25.00. For any orders over $25.00, add 10% to the total purchase price for shipping and handling, but do not include the $1.50 minimum shipping and handling charge. The formula for calculating a percentage is price * percent / 100. For example, the formula for calculating 10% of a $50.00 purchase price is 50 * 10 / 100, which results in a shipping and handling charge of $5.00. After you determine the total cost of the order (purchase plus shipping and handling), display it in an alert dialog box. Here is the code I have: <!DOCTYPE> <head> <title>Calculate Shipping</title> <script type="text/javascript"> function parseInt() { var salesPrice = document.salesForm.Price.value; var minCharge = salesPrice + 1.50; var shipping = salesPrice * 10/100; if (salesPrice <= 25) window.alert('Your sales total including shipping is $' + minCharge); else window.alert('Your sales total including shipping is $' + salesPrice + shipping); } </script> </head> <body> <form name="salesForm"> <div > <p>Enter Your Purchase Price</p> <input type="text" name="Price" /><br /><br /> <input type="button" name="Calculate" value="Calculate Shipping" onclick="parseInt ()" /> </div> </form> </body> </html> Everything works except for the math in the alert box. It will show an incorrect total...

    Read the article

  • Synchronize Data between a Silverlight ListBox and a User Control

    - by psheriff
    One of the great things about XAML is the powerful data-binding capabilities. If you load up a list box with a collection of objects, you can display detail data about each object without writing any C# or VB.NET code. Take a look at Figure 1 that shows a collection of Product objects in a list box. When you click on a list box you bind the current Product object selected in the list box to a set of controls in a user control with just a very simple Binding statement in XAML.  Figure 1: Synchronizing a ListBox to a User Control is easy with Data Binding Product and Products Classes To illustrate this data binding feature I am going to just create some local data instead of using a WCF service. The code below shows a Product class that has three properties, namely, ProductId, ProductName and Price. This class also has a constructor that takes 3 parameters and allows us to set the 3 properties in an instance of our Product class. C#public class Product{  public Product(int productId, string productName, decimal price)  {    ProductId = productId;    ProductName = productName;    Price = price;  }   public int ProductId { get; set; }  public string ProductName { get; set; }  public decimal Price { get; set; }} VBPublic Class Product  Public Sub New(ByVal _productId As Integer, _                 ByVal _productName As String, _                 ByVal _price As Decimal)    ProductId = _productId    ProductName = _productName    Price = _price  End Sub   Private mProductId As Integer  Private mProductName As String  Private mPrice As Decimal   Public Property ProductId() As Integer    Get      Return mProductId    End Get    Set(ByVal value As Integer)      mProductId = value    End Set  End Property   Public Property ProductName() As String    Get      Return mProductName    End Get    Set(ByVal value As String)      mProductName = value    End Set  End Property   Public Property Price() As Decimal    Get      Return mPrice    End Get    Set(ByVal value As Decimal)      mPrice = value    End Set  End PropertyEnd Class To fill up a list box you need a collection class of Product objects. The code below creates a generic collection class of Product objects. In the constructor of the Products class I have hard-coded five product objects and added them to the collection. In a real-world application you would get your data through a call to service to fill the list box, but for simplicity and just to illustrate the data binding, I am going to just hard code the data. C#public class Products : List<Product>{  public Products()  {    this.Add(new Product(1, "Microsoft VS.NET 2008", 1000));    this.Add(new Product(2, "Microsoft VS.NET 2010", 1000));    this.Add(new Product(3, "Microsoft Silverlight 4", 1000));    this.Add(new Product(4, "Fundamentals of N-Tier eBook", 20));    this.Add(new Product(5, "ASP.NET Security eBook", 20));  }} VBPublic Class Products  Inherits List(Of Product)   Public Sub New()    Me.Add(New Product(1, "Microsoft VS.NET 2008", 1000))    Me.Add(New Product(2, "Microsoft VS.NET 2010", 1000))    Me.Add(New Product(3, "Microsoft Silverlight 4", 1000))    Me.Add(New Product(4, "Fundamentals of N-Tier eBook", 20))    Me.Add(New Product(5, "ASP.NET Security eBook", 20))  End SubEnd Class The Product Detail User Control Below is a user control (named ucProduct) that is used to display the product detail information seen in the bottom portion of Figure 1. This is very basic XAML that just creates a text block and a text box control for each of the three properties in the Product class. Notice the {Binding Path=[PropertyName]} on each of the text box controls. This means that if the DataContext property of this user control is set to an instance of a Product class, then the data in the properties of that Product object will be displayed in each of the text boxes. <UserControl x:Class="SL_SyncListBoxAndUserControl_CS.ucProduct"  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  HorizontalAlignment="Left"  VerticalAlignment="Top">  <Grid Margin="4">    <Grid.RowDefinitions>      <RowDefinition Height="Auto" />      <RowDefinition Height="Auto" />      <RowDefinition Height="Auto" />    </Grid.RowDefinitions>    <Grid.ColumnDefinitions>      <ColumnDefinition MinWidth="120" />      <ColumnDefinition />    </Grid.ColumnDefinitions>    <TextBlock Grid.Row="0"               Grid.Column="0"               Text="Product Id" />    <TextBox Grid.Row="0"             Grid.Column="1"             Text="{Binding Path=ProductId}" />    <TextBlock Grid.Row="1"               Grid.Column="0"               Text="Product Name" />    <TextBox Grid.Row="1"             Grid.Column="1"             Text="{Binding Path=ProductName}" />    <TextBlock Grid.Row="2"               Grid.Column="0"               Text="Price" />    <TextBox Grid.Row="2"             Grid.Column="1"             Text="{Binding Path=Price}" />  </Grid></UserControl> Synchronize ListBox with User Control You are now ready to fill the list box with the collection class of Product objects and then bind the SelectedItem of the list box to the Product detail user control. The XAML below is the complete code for Figure 1. <UserControl x:Class="SL_SyncListBoxAndUserControl_CS.MainPage"  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  xmlns:src="clr-namespace:SL_SyncListBoxAndUserControl_CS"  VerticalAlignment="Top"  HorizontalAlignment="Left">  <UserControl.Resources>    <src:Products x:Key="productCollection" />  </UserControl.Resources>  <Grid x:Name="LayoutRoot"        Margin="4"        Background="White">    <Grid.RowDefinitions>      <RowDefinition Height="Auto" />      <RowDefinition Height="*" />    </Grid.RowDefinitions>    <ListBox x:Name="lstData"             Grid.Row="0"             BorderBrush="Black"             BorderThickness="1"             ItemsSource="{Binding                   Source={StaticResource productCollection}}"             DisplayMemberPath="ProductName" />    <src:ucProduct x:Name="prodDetail"                   Grid.Row="1"                   DataContext="{Binding ElementName=lstData,                                          Path=SelectedItem}" />  </Grid></UserControl> The first step to making this happen is to reference the Silverlight project (SL_SyncListBoxAndUserControl_CS) where the Product and Products classes are located. I added this namespace and assigned it a namespace prefix of “src” as shown in the line below: xmlns:src="clr-namespace:SL_SyncListBoxAndUserControl_CS" Next, to use the data from an instance of the Products collection, you create a UserControl.Resources section in the XAML and add a tag that creates an instance of the Products class and assigns it a key of “productCollection”.   <UserControl.Resources>    <src:Products x:Key="productCollection" />  </UserControl.Resources> Next, you bind the list box to this productCollection object using the ItemsSource property. You bind the ItemsSource of the list box to the static resource named productCollection. You can then set the DisplayMemberPath attribute of the list box to any property of the Product class that you want. In the XAML below I used the ProductName property. <ListBox x:Name="lstData"         ItemsSource="{Binding             Source={StaticResource productCollection}}"         DisplayMemberPath="ProductName" /> You now need to create an instance of the ucProduct user contol below the list box. You do this by once again referencing the “src” namespace and typing in the name of the user control. You then set the DataContext property on this user control to a binding. The binding uses the ElementName attribute to bind to the list box name, in this case “lstData”. The Path of the data is SelectedItem. These two attributes together tell Silverlight to bind the DataContext to the selected item of the list box. That selected item is a Product object. So, once this is bound, the bindings on each text box in the user control are updated and display the current product information. <src:ucProduct x:Name="prodDetail"               DataContext="{Binding ElementName=lstData,                                      Path=SelectedItem}" /> Summary Once you understand the basics of data binding in XAML, you eliminate a lot code that is otherwise needed to move data into controls and out of controls back into an object. Connecting two controls together is easy by just binding using the ElementName and Path properties of the Binding markup extension. Another good tip out of this blog is use user controls and set the DataContext of the user control to have all of the data on the user control update through the bindings. NOTE: You can download the complete sample code (in both VB and C#) at my website. http://www.pdsa.com/downloads. Choose Tips & Tricks, then "SL – Synchronize List Box Data with User Control" from the drop-down. Good Luck with your Coding,Paul Sheriff ** SPECIAL OFFER FOR MY BLOG READERS **Visit http://www.pdsa.com/Event/Blog for a free eBook on "Fundamentals of N-Tier".

    Read the article

  • Read XML Files using LINQ to XML and Extension Methods

    - by psheriff
    In previous blog posts I have discussed how to use XML files to store data in your applications. I showed you how to read those XML files from your project and get XML from a WCF service. One of the problems with reading XML files is when elements or attributes are missing. If you try to read that missing data, then a null value is returned. This can cause a problem if you are trying to load that data into an object and a null is read. This blog post will show you how to create extension methods to detect null values and return valid values to load into your object. The XML Data An XML data file called Product.xml is located in the \Xml folder of the Silverlight sample project for this blog post. This XML file contains several rows of product data that will be used in each of the samples for this post. Each row has 4 attributes; namely ProductId, ProductName, IntroductionDate and Price. <Products>  <Product ProductId="1"           ProductName="Haystack Code Generator for .NET"           IntroductionDate="07/01/2010"  Price="799" />  <Product ProductId="2"           ProductName="ASP.Net Jumpstart Samples"           IntroductionDate="05/24/2005"  Price="0" />  ...  ...</Products> The Product Class Just as you create an Entity class to map each column in a table to a property in a class, you should do the same for an XML file too. In this case you will create a Product class with properties for each of the attributes in each element of product data. The following code listing shows the Product class. public class Product : CommonBase{  public const string XmlFile = @"Xml/Product.xml";   private string _ProductName;  private int _ProductId;  private DateTime _IntroductionDate;  private decimal _Price;   public string ProductName  {    get { return _ProductName; }    set {      if (_ProductName != value) {        _ProductName = value;        RaisePropertyChanged("ProductName");      }    }  }   public int ProductId  {    get { return _ProductId; }    set {      if (_ProductId != value) {        _ProductId = value;        RaisePropertyChanged("ProductId");      }    }  }   public DateTime IntroductionDate  {    get { return _IntroductionDate; }    set {      if (_IntroductionDate != value) {        _IntroductionDate = value;        RaisePropertyChanged("IntroductionDate");      }    }  }   public decimal Price  {    get { return _Price; }    set {      if (_Price != value) {        _Price = value;        RaisePropertyChanged("Price");      }    }  }} NOTE: The CommonBase class that the Product class inherits from simply implements the INotifyPropertyChanged event in order to inform your XAML UI of any property changes. You can see this class in the sample you download for this blog post. Reading Data When using LINQ to XML you call the Load method of the XElement class to load the XML file. Once the XML file has been loaded, you write a LINQ query to iterate over the “Product” Descendants in the XML file. The “select” portion of the LINQ query creates a new Product object for each row in the XML file. You retrieve each attribute by passing each attribute name to the Attribute() method and retrieving the data from the “Value” property. The Value property will return a null if there is no data, or will return the string value of the attribute. The Convert class is used to convert the value retrieved into the appropriate data type required by the Product class. private void LoadProducts(){  XElement xElem = null;   try  {    xElem = XElement.Load(Product.XmlFile);     // The following will NOT work if you have missing attributes    var products =         from elem in xElem.Descendants("Product")        orderby elem.Attribute("ProductName").Value        select new Product        {          ProductId = Convert.ToInt32(            elem.Attribute("ProductId").Value),          ProductName = Convert.ToString(            elem.Attribute("ProductName").Value),          IntroductionDate = Convert.ToDateTime(            elem.Attribute("IntroductionDate").Value),          Price = Convert.ToDecimal(elem.Attribute("Price").Value)        };     lstData.DataContext = products;  }  catch (Exception ex)  {    MessageBox.Show(ex.Message);  }} This is where the problem comes in. If you have any missing attributes in any of the rows in the XML file, or if the data in the ProductId or IntroductionDate is not of the appropriate type, then this code will fail! The reason? There is no built-in check to ensure that the correct type of data is contained in the XML file. This is where extension methods can come in real handy. Using Extension Methods Instead of using the Convert class to perform type conversions as you just saw, create a set of extension methods attached to the XAttribute class. These extension methods will perform null-checking and ensure that a valid value is passed back instead of an exception being thrown if there is invalid data in your XML file. private void LoadProducts(){  var xElem = XElement.Load(Product.XmlFile);   var products =       from elem in xElem.Descendants("Product")      orderby elem.Attribute("ProductName").Value      select new Product      {        ProductId = elem.Attribute("ProductId").GetAsInteger(),        ProductName = elem.Attribute("ProductName").GetAsString(),        IntroductionDate =            elem.Attribute("IntroductionDate").GetAsDateTime(),        Price = elem.Attribute("Price").GetAsDecimal()      };   lstData.DataContext = products;} Writing Extension Methods To create an extension method you will create a class with any name you like. In the code listing below is a class named XmlExtensionMethods. This listing just shows a couple of the available methods such as GetAsString and GetAsInteger. These methods are just like any other method you would write except when you pass in the parameter you prefix the type with the keyword “this”. This lets the compiler know that it should add this method to the class specified in the parameter. public static class XmlExtensionMethods{  public static string GetAsString(this XAttribute attr)  {    string ret = string.Empty;     if (attr != null && !string.IsNullOrEmpty(attr.Value))    {      ret = attr.Value;    }     return ret;  }   public static int GetAsInteger(this XAttribute attr)  {    int ret = 0;    int value = 0;     if (attr != null && !string.IsNullOrEmpty(attr.Value))    {      if(int.TryParse(attr.Value, out value))        ret = value;    }     return ret;  }   ...  ...} Each of the methods in the XmlExtensionMethods class should inspect the XAttribute to ensure it is not null and that the value in the attribute is not null. If the value is null, then a default value will be returned such as an empty string or a 0 for a numeric value. Summary Extension methods are a great way to simplify your code and provide protection to ensure problems do not occur when reading data. You will probably want to create more extension methods to handle XElement objects as well for when you use element-based XML. Feel free to extend these extension methods to accept a parameter which would be the default value if a null value is detected, or any other parameters you wish. NOTE: You can download the complete sample code at my website. http://www.pdsa.com/downloads. Choose “Tips & Tricks”, then "Read XML Files using LINQ to XML and Extension Methods" from the drop-down. Good Luck with your Coding,Paul D. Sheriff  

    Read the article

  • Calculate average gas prices by year in excel

    - by ghostryder111
    I have 3 columns, A=Date, B=Price, C=Grade in Excel. I want to calculate the average price of fuel for each year and an overall average of all years by grade. The data table looks like this Date | Price | Grade 2012-05-01 | $3.49 | Regular 2012-06-07 | $3.58 | Regular 2012-04-01 | $3.98 | Premium 2012-02-17 | $3.87 | Premium 2013-01-01 | $3.49 | Regular 2013-02-01 | $3.89 | Premium 2013-03-06 | $3.89 | Premium 2013-03-09 | $3.45 | Regular The output should look something like this: Year | Regular | Premium 2012 | 3.43 | 3.67 2013 | 3.45 | 3.73 All | 3.44 | 3.70

    Read the article

  • XSL to show highest number of copies in catalog.xml file

    - by SANJAY RAO
    In this the catalog.xml file. I have two books who have the same inventory (i.e. 20). I want to write an XSL file that will display the highest number of copies of a book in a catalog. If there are two or more books of the same inventory then they have to be displayed. <catalog> <Book> <sku>12345</sku> <title>Beauty Secrets</title> <condition>New</condition> <current_inventory>20</current_inventory> <price>99.99</price> </Book> <Book> <sku>54321</sku> <title>Picturescapes</title> <current_inventory>20</current_inventory> <condition>New</condition> <price>50.00</price> </Book> <Book> <sku>33333</sku> <title>Tourist Perspectives</title> <condition>New</condition> <current_inventory>0</current_inventory> <price>75.00</price> </Book> <Book> <sku>10001</sku> <title>Fire in the Sky</title> <condition>Used</condition> <current_inventory>0</current_inventory> <price>10.00</price> </Book> </catalog> Below is my catalog3.xsl file which is able to display only one out of the two books: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > <xsl:variable name="max"/> <xsl:template match="/"> <html> <body> <h2>Titles of Books for which Most Copies are Available</h2> <table border="2"> <tr bgcolor="#9acd32"> <th>Title</th> <th>No of Copies</th> </tr> <xsl:apply-templates/> </table> </body> </html> </xsl:template> <xsl:template match="catalog"> <xsl:for-each select="Book"> <xsl:sort select="current_inventory" data-type="number" order="descending"/> <tr> <xsl:if test="position()= 1"> <p><xsl:value-of select="$max = "/></p> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="current_inventory"/></td> </xsl:if> </tr> </xsl:for-each> </xsl:template> </xsl:stylesheet> Could anybody correct me to achieve my goal of displaying all the copies having the same maximum inventory in the catalog. Thanks.

    Read the article

  • Binding DataTable To GridView, But No Rows In GridViewRowCollection Despite GridView Population?

    - by KSwift87
    Problem: I've coded a GridView in the markup in a page. I have coded a DataTable in the code-behind that takes data from a collection of custom objects. I then bind that DataTable to the GridView. (Specific problem mentioned a couple code-snippets below.) GridView Markup: <asp:GridView ID="gvCart" runat="server" CssClass="pList" AutoGenerateColumns="false" DataKeyNames="ProductID"> <Columns> <asp:BoundField DataField="ProductID" HeaderText="ProductID" /> <asp:BoundField DataField="Name" HeaderText="ProductName" /> <asp:ImageField DataImageUrlField="Thumbnail" HeaderText="Thumbnail"></asp:ImageField> <asp:BoundField DataField="Unit Price" HeaderText="Unit Price" /> <asp:TemplateField HeaderText="Quantity"> <ItemTemplate> <asp:TextBox ID="Quantity" runat="server" Text="<%# Bind('Quantity') %>" Width="25px"></asp:TextBox> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Total Price" HeaderText="Total Price" /> </Columns> </asp:GridView> DataTable Code-Behind: private void View(List<OrderItem> cart) { DataSet ds = new DataSet(); DataTable dt = ds.Tables.Add("Cart"); if (cart != null) { dt.Columns.Add("ProductID"); dt.Columns.Add("Name"); dt.Columns.Add("Thumbnail"); dt.Columns.Add("Unit Price"); dt.Columns.Add("Quantity"); dt.Columns.Add("Total Price"); foreach (OrderItem item in cart) { DataRow dr = dt.NewRow(); dr["ProductID"] = item.productId.ToString(); dr["Name"] = item.productName; dr["Thumbnail"] = ResolveUrl(item.productThumbnail); dr["Unit Price"] = "$" + item.productPrice.ToString(); dr["Quantity"] = item.productQuantity.ToString(); dr["Total Price"] = "$" + (item.productPrice * item.productQuantity).ToString(); dt.Rows.Add(dr); } gvCart.DataSource = dt; gvCart.DataBind(); gvCart.Width = 500; for (int counter = 0; counter < gvCart.Rows.Count; counter++) { gvCart.Rows[counter].Cells.Add(Common.createCell("<a href='cart.aspx?action=update&prodId=" + gvCart.Rows[counter].Cells[0].Text + "'>Update</a><br /><a href='cart.aspx?action='action=remove&prodId=" + gvCart.Rows[counter].Cells[0].Text + "/>Remove</a>")); } } } Error occurs below in the foreach - the GridViewRowCollection is empty! private void Update(string prodId) { List<OrderItem> cart = (List<OrderItem>)Session["cart"]; int uQty = 0; foreach (GridViewRow gvr in gvCart.Rows) { if (gvr.RowType == DataControlRowType.DataRow) { if (gvr.Cells[0].Text == prodId) { uQty = int.Parse(((TextBox)gvr.Cells[4].FindControl("Quantity")).Text); } } } Goal: I'm basically trying to find a way to update the data in my GridView (and more importantly my cart Session object) without having to do everything else I've seen online such as utilizing OnRowUpdate, etc. Could someone please tell me why gvCart.Rows is empty and/or how I could accomplish my goal without utilizing OnRowUpdate, etc.? When I execute this code, the GridView gets populated but for some reason I can't access any of its rows in the code-behind.

    Read the article

  • Adding view cart function

    - by user228390
    Hey guys need some help in adding a view cart button but I'm stuck not sure how to code it. any help? The way I have coded it is that when a user clicks 'add item' they will get a alert box with info about the total price but I want that to appear in the HTML file but only once I have clicked on 'view cart' and I need it to be in a table format with info about the name, sum, price of the items and total. any ideas how I can do this? here is my javascript var f,d,str,items,qnts,price,bag,total; function cart(){ f=document.forms[0]; d=f.getElementsByTagName('div'); var items=[];var qnts=[];price=[];bag=[] for(i=0,e=0;i<d.length;i++){ items[i]=d[i].getElementsByTagName('b')[0].innerHTML; qnts[i]=d[i].getElementsByTagName('select')[0].value; str=d[i].getElementsByTagName('p')[1].innerHTML; priceStart(str,i); if(qnts[i]!=0){bag.push(new Array()); ib=bag[bag.length-1]; ib.push(items[i]);ib.push(qnts[i]);ib.push(price[i]);ib.push(qnts[i]*price[i]);} } if(bag.length>0){ total=bag[0][3]; if(bag.length>1){for(t=1;t<bag.length;t++){total+=bag[t][3]}} alert(bag.join('\n')+'\n----------------\ntotal='+total) } } function priceStart(str,inx){for(j=0;j<str.length;j++){if(str.charAt(j)!=' ' && !isNaN(str.charAt(j))){priceEnd(j,str,inx);return }}} function priceEnd(j,str,inx){for(k=str.length;k>j;k--){if(str.charAt(k)!=' ' && !isNaN(str.charAt(k))){price[inx]=str.substring(j,k);return }}} and my HTML <script type="text/javascript" src="cart.js" /> </script> <link rel="stylesheet" type="text/css" href="shopping_cart.css" /> <title> A title </title> </head> <body> <form name="form1" method="post" action="data.php" > <div id="product1"> <p id="title1"><b>Star Wars Tie Interceptor</b></p> <img src="images/DS.jpg" /> <p id="price1">Price £39.99</p> <p><b>Qty</b></p> <select name="qty"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> <input type="button" value="Add to cart" onclick="cart()" /> </div>

    Read the article

  • Cart coding help

    - by user228390
    I've made a simple Javascript code for a shopping basket but now I have realised that I have made a error with making it and don't know how to fix it. What I have is Javascript file but I have also included the images source and the addtocart button as well, but What I am trying to do now is make 2 files one a .HTML file and another .JS file, but I can't get it to because when I make a button in the HTML file to call the function from the .JS file it won't work at all. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <HTML> <HEAD><TITLE>shopping</TITLE> <META http-equiv=Content-Type content="text/html; charset=UTF-8"> <STYLE type=text/CSS> fieldset{width:300px} legend{font-size:24px;font-family:comic sans ms;color:#004455} </STYLE> <META content="MSHTML 6.00.2900.2963" name=GENERATOR></HEAD> <BODY scroll="auto"> <div id="products"></div><hr> <div id="inCart"></div> <SCRIPT type="text/javascript"> var items=['Xbox~149.99','StuffedGizmo~19.98','GadgetyGoop~9.97']; var M='?'; var product=[]; var price=[]; var stuff=''; function wpf(product,price){var pf='<form><FIELDSET><LEGEND>'+product+'</LEGEND>'; pf+='<img src="../images/'+product+'.jpg" alt="'+product+'" ><p>price '+M+''+price+'</p> <b>Qty</b><SELECT>'; for(i=0;i<6;i++){pf+='<option value="'+i+'">'+i+'</option>'} pf+='</SELECT>'; pf+='<input type="button" value="Add to cart" onclick="cart()" /></FIELDSET></form>'; return pf } for(j=0;j<items.length;j++){ product[j]=items[j].substring(0,items[j].indexOf('~')); price[j]=items[j].substring(items[j].indexOf('~')+1,items[j].length); stuff+=''+wpf(product[j],price[j])+''; } document.getElementById('products').innerHTML=stuff; function cart(){ var order=[]; var tot=0 for(o=0,k=0;o<document.forms.length;o++){ if(document.forms[o].elements[1].value!=0){ qnty=document.forms[o].elements[1].value; order[k]=''+product[o]+'_'+qnty+'*'+price[o]+''; tot+=qnty*price[o];k++ } } document.getElementById('inCart').innerHTML=order.join('<br>')+'<h3>Total '+tot+'</h3>'; } </SCRIPT> <input type="button" value="Add to cart" onclick="cart()" /></FIELDSET></form> </BODY></HTML>

    Read the article

  • xslt to show most number of copies in catalog.xml file

    - by SANJAY RAO
    In this catalog.xml file i have two books who have the same inventory i.e 20 . I want to write a xsl file that will display the most number of copies of a book in a catalog .if there are two or more books of the same inventory then they have to be displayed . <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="catalog3.xsl"?> <!DOCTYPE catalog SYSTEM "catalog.dtd"> <catalog> <Book> <sku>12345</sku> <title>Beauty Secrets</title> <condition>New</condition> <current_inventory>20</current_inventory> <price>99.99</price> </Book> <Book> <sku>54321</sku> <title>Picturescapes</title> <current_inventory>20</current_inventory> <condition>New</condition> <price>50.00</price> </Book> <Book> <sku>33333</sku> <title>Tourist Perspectives</title> <condition>New</condition> <current_inventory>0</current_inventory> <price>75.00</price> </Book> <Book> <sku>10001</sku> <title>Fire in the Sky</title> <condition>Used</condition> <current_inventory>0</current_inventory> <price>10.00</price> </Book> below is my catalog3.xsl file which is able to display only one out of the two books <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:variable name="max"/> <xsl:template match="/"> <html> <body> <h2>Titles of Books for which Most Copies are Available</h2> <table border="2"> <tr bgcolor="#9acd32"> <th>Title</th> <th>No of Copies</th> </tr> <xsl:apply-templates/> </table> </body> </html> </xsl:template> <xsl:template match="catalog"> <xsl:for-each select="Book"> <xsl:sort select="current_inventory" data-type="number" order="descending"/> <tr> <xsl:if test="position()= 1"> <p><xsl:value-of select="$max = "/></p> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="current_inventory"/></td> </xsl:if> </tr> could anybody correct me to achieve my goal of displaying all the copies having the same maximum inventory in the catalog . Thanks .

    Read the article

  • Partial view is not rendering within the main view it's contained (instead it's rendered in it's own page)?

    - by JaJ
    I have a partial view that is contained in a simple index view. When I try to add a new object to my model and update my partial view to display that new object along with existing objects the partial view is rendered outside the page that it's contained? I'm using AJAX to update the partial view but what is wrong with the following code? Model: public class Product { public int ID { get; set; } public string Name { get; set; } [DataType(DataType.Currency)] public decimal Price { get; set; } } public class BoringStoreContext { List<Product> results = new List<Product>(); public BoringStoreContext() { Products = new List<Product>(); Products.Add(new Product() { ID = 1, Name = "Sure", Price = (decimal)(1.10) }); Products.Add(new Product() { ID = 2, Name = "Sure2", Price = (decimal)(2.10) }); } public List<Product> Products {get; set;} } public class ProductIndexViewModel { public Product NewProduct { get; set; } public IEnumerable<Product> Products { get; set; } } Index.cshtml View: @model AjaxPartialPageUpdates.Models.ProductIndexViewModel @using (Ajax.BeginForm("Index_AddItem", new AjaxOptions { UpdateTargetId = "productList" })) { <div> @Html.LabelFor(model => model.NewProduct.Name) @Html.EditorFor(model => model.NewProduct.Name) </div> <div> @Html.LabelFor(model => model.NewProduct.Price) @Html.EditorFor(model => model.NewProduct.Price) </div> <div> <input type="submit" value="Add Product" /> </div> } <div id='productList'> @{ Html.RenderPartial("ProductListControl", Model.Products); } </div> ProductListControl.cshtml Partial View @model IEnumerable<AjaxPartialPageUpdates.Models.Product> <table> <!-- Render the table headers. --> <tr> <th>Name</th> <th>Price</th> </tr> <!-- Render the name and price of each product. --> @foreach (var item in Model) { <tr> <td>@Html.DisplayFor(model => item.Name)</td> <td>@Html.DisplayFor(model => item.Price)</td> </tr> } </table> Controller: public class HomeController : Controller { public ActionResult Index() { BoringStoreContext db = new BoringStoreContext(); ProductIndexViewModel viewModel = new ProductIndexViewModel { NewProduct = new Product(), Products = db.Products }; return View(viewModel); } public ActionResult Index_AddItem(ProductIndexViewModel viewModel) { BoringStoreContext db = new BoringStoreContext(); db.Products.Add(viewModel.NewProduct); return PartialView("ProductListControl", db.Products); } }

    Read the article

  • Help with Jquery and multiple forms on a page.

    - by Will
    I have a several forms that are output from a database on the same page. It works fine when I don't use ajax. When I use Jquery it will only work for the first form. Could anyone point me in the right direction please? Jquery..... $('.updateSubmit').live('click', function() { var id = $('.id').val(); var hardSoft = $('.hardSoft').val(); var brand = $('.brand').val(); var subCat = $('.subCat').val(); var subSubCat = $('.subSubCat').val(); var tProduct = $('.tProduct').val(); var description = $('.description').val(); var quantity = $('.quantity').val(); var price = $('.price').val(); var tCondition = $('.tCondition').val(); var featured = $('.featured').val(); var theData = 'id=' + id + '&hardSoft=' + hardSoft + '&brand=' + brand + '&subCat=' + subCat + '&subSubCat=' + subSubCat + '&tProduct=' + tProduct +'&description=' + description + '&quantity=' + quantity + '&price=' + price + '&tCondition=' + tCondition + '&featured=' + featured; $.ajax ({ type: 'POST', url: '/updateGrab.php', data: theData, success: function(aaa) { $('.'+id).append('<div class="forSuccess">'+aaa+'</div>'); } // end success }); // end ajax return false; }); // end click and my php form...... while ($row = $stmt->fetch()) { echo " <form action='http://www.wbrock.com/updateGrab.php' method='post' name='".$id."'> <input type='hidden' class='id' name='id' value='".$id."' /> Hardware/Software <input type='text' class='hardSoft' name='hardSoft' value='".$hardSoft."' /> Brand <input type='text' class='brand' name='brand' value='".$brand."' /> Sub-category <input type='text' class='subCat' name='subCat' value='".$subCat."' /> Sub-Sub-Cat <input type='text' class='subSubCat' name='subSubCat' value='".$subSubCat."' /> Product <input type='text' class='tProduct' name='tProduct' value='".$tProduct."' /> Description <input type='text' class='description' name='description' value='".$description."' /> Qty <input type='text' class='quantity' name='quantity' value='".$quantity."' /> Price <input type='text' class='price' name='price' value='".$price."' /> Cond <input type='text' class='tCondition' name='tCondition'value='".$tCondition."' /> Featured <input type='text' class='featured' name='featured' value='".$featured."' /> <input type='submit' id='".$id."' class='updateSubmit' name='updateSubmit' value='Update' /> </form> <span class='".$id."'></span> "; // end echo } // end while loop from database This is the first time I've posted here so sorry if its not in the right format. Thanks in advance for the help.

    Read the article

  • SQLAuthority News – Microsoft SQL Server 2005/2008 Query Optimization & Performance Tuning Training

    - by pinaldave
    Last 3 days to register for the courses. This is one time offer with big discount. The deadline for the course registration is 5th May, 2010. There are two different courses are offered by Solid Quality Mentors 1) Microsoft SQL Server 2005/2008 Query Optimization & Performance Tuning – Pinal Dave Date: May 12-14, 2010 Price: Rs. 14,000/person for 3 days Discount Code: ‘SQLAuthority.com’ Effective Price: Rs. 11,000/person for 3 days 2) SharePoint 2010 – Joy Rathnayake Date: May 10-11, 2010 Price: Rs. 11,000/person for 3 days Discount Code: ‘SQLAuthority.com’ Effective Price: Rs. 8,000/person for 2 days Download the complete PDF brochure. To register, either send an email to [email protected] or call +91 95940 43399. Feel free to drop me an email at pinal “at” SQLAuthority.com for any additional information and clarification. Training Venue: Abridge Solutions, #90/B/C/3/1, Ganesh GHR & MSY Plaza, Vittalrao Nagar, Near Image Hospital, Madhapur, Hyderabad – 500 081. Additionally there is special program of SolidQ India Insider. This is only available to first few registrants of the courses only. Read more details about the course here. Read my TechEd India 2010 experience here. Reference: Pinal Dave (http://blog.SQLAuthority.com) Filed under: Pinal Dave, SQL, SQL Authority, SQL Optimization, SQL Performance, SQL Query, SQL Server, SQL Tips and Tricks, SQL Training, SQLAuthority News, T SQL, Technology

    Read the article

  • SQLAuthority News – Public Training Classes In Hyderabad 12-14 May – SQL and 10-11 May SharePoint

    - by pinaldave
    There were lots of request about providing more details for the blog post through email address specified in the article SQLAuthority News – Public Training Classes In Hyderabad 12-14 May – Microsoft SQL Server 2005/2008 Query Optimization & Performance Tuning. Here is the complete brochure of the course. There are two different courses are offered by Solid Quality Mentors 1) Microsoft SQL Server 2005/2008 Query Optimization & Performance Tuning – Pinal Dave Date: May 12-14, 2010 Price: Rs. 14,000/person for 3 days Discount Code: ‘SQLAuthority.com‘ Effective Price: Rs. 11,000/person for 3 days 2) SharePoint 2010 – Joy Rathnayake Date: May 10-11, 2010 Price: Rs. 11,000/person for 3 days Discount Code: ‘SQLAuthority.com’ Effective Price: Rs. 8,000/person for 3 days Download the complete PDF brochure. Additionally there is special program of SolidQ India Insider. I will provide the details for the same very soon. Please do send me email if you need any additional details. Reference: Pinal Dave (http://blog.SQLAuthority.com) Filed under: Pinal Dave, SQL, SQL Authority, SQL Optimization, SQL Performance, SQL Query, SQL Server, SQL Tips and Tricks, SQL Training, SQLAuthority News, T SQL, Technology

    Read the article

  • SQLAuthority News – Public Training Classes In Hyderabad 12-14 May – SQL and 10-11 May SharePoint

    - by pinaldave
    There were lots of request about providing more details for the blog post through email address specified in the article SQLAuthority News – Public Training Classes In Hyderabad 12-14 May – Microsoft SQL Server 2005/2008 Query Optimization & Performance Tuning. Here is the complete brochure of the course. There are two different courses are offered by Solid Quality Mentors 1) Microsoft SQL Server 2005/2008 Query Optimization & Performance Tuning – Pinal Dave Date: May 12-14, 2010 Price: Rs. 14,000/person for 3 days Discount Code: ‘SQLAuthority.com‘ Effective Price: Rs. 11,000/person for 3 days 2) SharePoint 2010 – Joy Rathnayake Date: May 10-11, 2010 Price: Rs. 11,000/person for 3 days Discount Code: ‘SQLAuthority.com’ Effective Price: Rs. 8,000/person for 3 days Download the complete PDF brochure. Additionally there is special program of SolidQ India Insider. I will provide the details for the same very soon. Please do send me email if you need any additional details. Reference: Pinal Dave (http://blog.SQLAuthority.com) Filed under: Pinal Dave, SQL, SQL Authority, SQL Optimization, SQL Performance, SQL Query, SQL Server, SQL Tips and Tricks, SQL Training, SQLAuthority News, T SQL, Technology

    Read the article

  • ASP.NET MVC Validation Complete

    - by Ricardo Peres
    OK, so let’s talk about validation. Most people are probably familiar with the out of the box validation attributes that MVC knows about, from the System.ComponentModel.DataAnnotations namespace, such as EnumDataTypeAttribute, RequiredAttribute, StringLengthAttribute, RangeAttribute, RegularExpressionAttribute and CompareAttribute from the System.Web.Mvc namespace. All of these validators inherit from ValidationAttribute and perform server as well as client-side validation. In order to use them, you must include the JavaScript files MicrosoftMvcValidation.js, jquery.validate.js or jquery.validate.unobtrusive.js, depending on whether you want to use Microsoft’s own library or jQuery. No significant difference exists, but jQuery is more extensible. You can also create your own attribute by inheriting from ValidationAttribute, but, if you want to have client-side behavior, you must also implement IClientValidatable (all of the out of the box validation attributes implement it) and supply your own JavaScript validation function that mimics its server-side counterpart. Of course, you must reference the JavaScript file where the declaration function is. Let’s see an example, validating even numbers. First, the validation attribute: 1: [Serializable] 2: [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] 3: public class IsEvenAttribute : ValidationAttribute, IClientValidatable 4: { 5: protected override ValidationResult IsValid(Object value, ValidationContext validationContext) 6: { 7: Int32 v = Convert.ToInt32(value); 8:  9: if (v % 2 == 0) 10: { 11: return (ValidationResult.Success); 12: } 13: else 14: { 15: return (new ValidationResult("Value is not even")); 16: } 17: } 18:  19: #region IClientValidatable Members 20:  21: public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 22: { 23: yield return (new ModelClientValidationRule() { ValidationType = "iseven", ErrorMessage = "Value is not even" }); 24: } 25:  26: #endregion 27: } The iseven validation function is declared like this in JavaScript, using jQuery validation: 1: jQuery.validator.addMethod('iseven', function (value, element, params) 2: { 3: return (true); 4: return ((parseInt(value) % 2) == 0); 5: }); 6:  7: jQuery.validator.unobtrusive.adapters.add('iseven', [], function (options) 8: { 9: options.rules['iseven'] = options.params; 10: options.messages['iseven'] = options.message; 11: }); Do keep in mind that this is a simple example, for example, we are not using parameters, which may be required for some more advanced scenarios. As a side note, if you implement a custom validator that also requires a JavaScript function, you’ll probably want them together. One way to achieve this is by including the JavaScript file as an embedded resource on the same assembly where the custom attribute is declared. You do this by having its Build Action set as Embedded Resource inside Visual Studio: Then you have to declare an attribute at assembly level, perhaps in the AssemblyInfo.cs file: 1: [assembly: WebResource("SomeNamespace.IsEven.js", "text/javascript")] In your views, if you want to include a JavaScript file from an embedded resource you can use this code: 1: public static class UrlExtensions 2: { 3: private static readonly MethodInfo getResourceUrlMethod = typeof(AssemblyResourceLoader).GetMethod("GetWebResourceUrlInternal", BindingFlags.NonPublic | BindingFlags.Static); 4:  5: public static IHtmlString Resource<TType>(this UrlHelper url, String resourceName) 6: { 7: return (Resource(url, typeof(TType).Assembly.FullName, resourceName)); 8: } 9:  10: public static IHtmlString Resource(this UrlHelper url, String assemblyName, String resourceName) 11: { 12: String resourceUrl = getResourceUrlMethod.Invoke(null, new Object[] { Assembly.Load(assemblyName), resourceName, false, false, null }).ToString(); 13: return (new HtmlString(resourceUrl)); 14: } 15: } And on the view: 1: <script src="<%: this.Url.Resource("SomeAssembly", "SomeNamespace.IsEven.js") %>" type="text/javascript"></script> Then there’s the CustomValidationAttribute. It allows externalizing your validation logic to another class, so you have to tell which type and method to use. The method can be static as well as instance, if it is instance, the class cannot be abstract and must have a public parameterless constructor. It can be applied to a property as well as a class. It does not, however, support client-side validation. Let’s see an example declaration: 1: [CustomValidation(typeof(ProductValidator), "OnValidateName")] 2: public String Name 3: { 4: get; 5: set; 6: } The validation method needs this signature: 1: public static ValidationResult OnValidateName(String name) 2: { 3: if ((String.IsNullOrWhiteSpace(name) == false) && (name.Length <= 50)) 4: { 5: return (ValidationResult.Success); 6: } 7: else 8: { 9: return (new ValidationResult(String.Format("The name has an invalid value: {0}", name), new String[] { "Name" })); 10: } 11: } Note that it can be either static or instance and it must return a ValidationResult-derived class. ValidationResult.Success is null, so any non-null value is considered a validation error. The single method argument must match the property type to which the attribute is attached to or the class, in case it is applied to a class: 1: [CustomValidation(typeof(ProductValidator), "OnValidateProduct")] 2: public class Product 3: { 4: } The signature must thus be: 1: public static ValidationResult OnValidateProduct(Product product) 2: { 3: } Continuing with attribute-based validation, another possibility is RemoteAttribute. This allows specifying a controller and an action method just for performing the validation of a property or set of properties. This works in a client-side AJAX way and it can be very useful. Let’s see an example, starting with the attribute declaration and proceeding to the action method implementation: 1: [Remote("Validate", "Validation")] 2: public String Username 3: { 4: get; 5: set; 6: } The controller action method must contain an argument that can be bound to the property: 1: public ActionResult Validate(String username) 2: { 3: return (this.Json(true, JsonRequestBehavior.AllowGet)); 4: } If in your result JSON object you include a string instead of the true value, it will consider it as an error, and the validation will fail. This string will be displayed as the error message, if you have included it in your view. You can also use the remote validation approach for validating your entire entity, by including all of its properties as included fields in the attribute and having an action method that receives an entity instead of a single property: 1: [Remote("Validate", "Validation", AdditionalFields = "Price")] 2: public String Name 3: { 4: get; 5: set; 6: } 7:  8: public Decimal Price 9: { 10: get; 11: set; 12: } The action method will then be: 1: public ActionResult Validate(Product product) 2: { 3: return (this.Json("Product is not valid", JsonRequestBehavior.AllowGet)); 4: } Only the property to which the attribute is applied and the additional properties referenced by the AdditionalFields will be populated in the entity instance received by the validation method. The same rule previously stated applies, if you return anything other than true, it will be used as the validation error message for the entity. The remote validation is triggered automatically, but you can also call it explicitly. In the next example, I am causing the full entity validation, see the call to serialize(): 1: function validate() 2: { 3: var form = $('form'); 4: var data = form.serialize(); 5: var url = '<%: this.Url.Action("Validation", "Validate") %>'; 6:  7: var result = $.ajax 8: ( 9: { 10: type: 'POST', 11: url: url, 12: data: data, 13: async: false 14: } 15: ).responseText; 16:  17: if (result) 18: { 19: //error 20: } 21: } Finally, by implementing IValidatableObject, you can implement your validation logic on the object itself, that is, you make it self-validatable. This will only work server-side, that is, the ModelState.IsValid property will be set to false on the controller’s action method if the validation in unsuccessful. Let’s see how to implement it: 1: public class Product : IValidatableObject 2: { 3: public String Name 4: { 5: get; 6: set; 7: } 8:  9: public Decimal Price 10: { 11: get; 12: set; 13: } 14:  15: #region IValidatableObject Members 16: 17: public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 18: { 19: if ((String.IsNullOrWhiteSpace(this.Name) == true) || (this.Name.Length > 50)) 20: { 21: yield return (new ValidationResult(String.Format("The name has an invalid value: {0}", this.Name), new String[] { "Name" })); 22: } 23: 24: if ((this.Price <= 0) || (this.Price > 100)) 25: { 26: yield return (new ValidationResult(String.Format("The price has an invalid value: {0}", this.Price), new String[] { "Price" })); 27: } 28: } 29: 30: #endregion 31: } The errors returned will be matched against the model properties through the MemberNames property of the ValidationResult class and will be displayed in their proper labels, if present on the view. On the controller action method you can check for model validity by looking at ModelState.IsValid and you can get actual error messages and related properties by examining all of the entries in the ModelState dictionary: 1: Dictionary<String, String> errors = new Dictionary<String, String>(); 2:  3: foreach (KeyValuePair<String, ModelState> keyValue in this.ModelState) 4: { 5: String key = keyValue.Key; 6: ModelState modelState = keyValue.Value; 7:  8: foreach (ModelError error in modelState.Errors) 9: { 10: errors[key] = error.ErrorMessage; 11: } 12: } And these are the ways to perform date validation in ASP.NET MVC. Don’t forget to use them!

    Read the article

  • Ajax-based data loading using jQuery.load() function in ASP.NET

    - by hajan
    In general, jQuery has made Ajax very easy by providing low-level interface, shorthand methods and helper functions, which all gives us great features of handling Ajax requests in our ASP.NET Webs. The simplest way to load data from the server and place the returned HTML in browser is to use the jQuery.load() function. The very firs time when I started playing with this function, I didn't believe it will work that much easy. What you can do with this method is simply call given url as parameter to the load function and display the content in the selector after which this function is chained. So, to clear up this, let me give you one very simple example: $("#result").load("AjaxPages/Page.html"); As you can see from the above image, after clicking the ‘Load Content’ button which fires the above code, we are making Ajax Get and the Response is the entire page HTML. So, rather than using (old) iframes, you can now use this method to load other html pages inside the page from where the script with load function is called. This method is equivalent to the jQuery Ajax Get method $.get(url, data, function () { }) only that the $.load() is method rather than global function and has an implicit callback function. To provide callback to your load, you can simply add function as second parameter, see example: $("#result").load("AjaxPages/Page.html", function () { alert("Page.html has been loaded successfully!") }); Since load is part of the chain which is follower of the given jQuery Selector where the content should be loaded, it means that the $.load() function won't execute if there is no such selector found within the DOM. Another interesting thing to mention, and maybe you've asked yourself is how we know if GET or POST method type is executed? It's simple, if we provide 'data' as second parameter to the load function, then POST is used, otherwise GET is assumed. POST $("#result").load("AjaxPages/Page.html", { "name": "hajan" }, function () { ////callback function implementation });   GET $("#result").load("AjaxPages/Page.html", function () { ////callback function implementation });   Another important feature that $.load() has ($.get() does not) is loading page fragments. Using jQuery's selector capability, you can do this: $("#result").load("AjaxPages/Page.html #resultTable"); In our Page.html, the content now is: So, after the call, only the table with id resultTable will load in our page.   As you can see, we have loaded only the table with id resultTable (1) inside div with id result (2). This is great feature since we won't need to filter the returned HTML content again in our callback function on the master page from where we have called $.load() function. Besides the fact that you can simply call static HTML pages, you can also use this function to load dynamic ASPX pages or ASP.NET ASHX Handlers . Lets say we have another page (ASPX) in our AjaxPages folder with name GetProducts.aspx. This page has repeater control (or anything you want to bind dynamic server-side content) that displays set of data in it. Now, I want to filter the data in the repeater based on the Query String parameter provided when calling that page. For example, if I call the page using GetProducts.aspx?category=computers, it will load only computers… so, this will filter the products automatically by given category. The example ASPX code of GetProducts.aspx page is: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GetProducts.aspx.cs" Inherits="WebApplication1.AjaxPages.GetProducts" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <table id="tableProducts"> <asp:Repeater ID="rptProducts" runat="server"> <HeaderTemplate> <tr> <th>Product</th> <th>Price</th> <th>Category</th> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td> <%# Eval("ProductName")%> </td> <td> <%# Eval("Price") %> </td> <td> <%# Eval("Category") %> </td> </tr> </ItemTemplate> </asp:Repeater> </ul> </div> </form> </body> </html> The C# code-behind sample code is: public partial class GetProducts : System.Web.UI.Page { public List<Product> products; protected override void OnInit(EventArgs e) { LoadSampleProductsData(); //load sample data base.OnInit(e); } protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString.Count > 0) { if (!string.IsNullOrEmpty(Request.QueryString["category"])) { string category = Request.QueryString["category"]; //get query string into string variable //filter products sample data by category using LINQ //and add the collection as data source to the repeater rptProducts.DataSource = products.Where(x => x.Category == category); rptProducts.DataBind(); //bind repeater } } } //load sample data method public void LoadSampleProductsData() { products = new List<Product>(); products.Add(new Product() { Category = "computers", Price = 200, ProductName = "Dell PC" }); products.Add(new Product() { Category = "shoes", Price = 90, ProductName = "Nike" }); products.Add(new Product() { Category = "shoes", Price = 66, ProductName = "Adidas" }); products.Add(new Product() { Category = "computers", Price = 210, ProductName = "HP PC" }); products.Add(new Product() { Category = "shoes", Price = 85, ProductName = "Puma" }); } } //sample Product class public class Product { public string ProductName { get; set; } public decimal Price { get; set; } public string Category { get; set; } } Mainly, I just have sample data loading function, Product class and depending of the query string, I am filtering the products list using LINQ Where statement. If we run this page without query string, it will show no data. If we call the page with category query string, it will filter automatically. Example: /AjaxPages/GetProducts.aspx?category=shoes The result will be: or if we use category=computers, like this /AjaxPages/GetProducts.aspx?category=computers, the result will be: So, now using jQuery.load() function, we can call this page with provided query string parameter and load appropriate content… The ASPX code in our Default.aspx page, which will call the AjaxPages/GetProducts.aspx page using jQuery.load() function is: <asp:RadioButtonList ID="rblProductCategory" runat="server"> <asp:ListItem Text="Shoes" Value="shoes" Selected="True" /> <asp:ListItem Text="Computers" Value="computers" /> </asp:RadioButtonList> <asp:Button ID="btnLoadProducts" runat="server" Text="Load Products" /> <!-- Here we will load the products, based on the radio button selection--> <div id="products"></div> </form> The jQuery code: $("#<%= btnLoadProducts.ClientID %>").click(function (event) { event.preventDefault(); //preventing button's default behavior var selectedRadioButton = $("#<%= rblProductCategory.ClientID %> input:checked").val(); //call GetProducts.aspx with the category query string for the selected category in radio button list //filter and get only the #tableProducts content inside #products div $("#products").load("AjaxPages/GetProducts.aspx?category=" + selectedRadioButton + " #tableProducts"); }); The end result: You can download the code sample from here. You can read more about jQuery.load() function here. I hope this was useful blog post for you. Please do let me know your feedback. Best Regards, Hajan

    Read the article

  • Ruby on Rails - Belongs_to and Active Admin not creating foreign ID

    - by Milo
    I have the following setup: class Category < ActiveRecord::Base has_many :products end class Product < ActiveRecord::Base belongs_to :category has_attached_file :photo, :styles => { :medium => "300x300>", :thumb => "200x200>" } validates_attachment_content_type :photo, :content_type => /\Aimage\/.*\Z/ end ActiveAdmin.register Product do permit_params :title, :price, :slideshow, :photo, :category form do |f| f.inputs "Product Details" do f.input :title f.input :category f.input :price f.input :slideshow f.input :photo, :required => false, :as => :file end f.actions end show do |ad| attributes_table do row :title row :category row :photo do image_tag(ad.photo.url(:medium)) end end end index do column :id column :title column :category column :price do |product| number_to_currency product.price end actions end class ProductController < ApplicationController def create @product = Product.create(params[:id]) end end Every time I make a product item in activeadmin the category comes up empty. It wont populate the column category_id for the product. It just leaves it empty. What am I doing wrong?

    Read the article

  • Suggestions for a CMS markup language for PHP

    - by Yanick Rochon
    As a learning experience, and as project, I am attempting to write a CMS module for ZF2. One of the functionality I would like to have is the possibility of adding dynamic contents in the pages by calling PHP functions in the view scripts. However, I do not want to give the users freedom in writing PHP code directly inside the page content, but rather implement custom view helpers (or widgets) to handle logic. For example: calling partial, partialLoop, url, etc. specifying arguments and all. I liked the idea of extending Markdown but this would get complicated when trying to add custom CSS class to elements, etc. Then I had the idea of simply doing a preg_replace on some patterns. For example, the string : ### partialLoop:['partials/display.phtml',[{id:'p1',price:4.99},{id:'p2',price:12.34}]] ### would be replaced by <?php echo $this->partialLoop('partials/display.phtml', array(array('id'=>'p1','price'=>4.99),array('id'=>'p2','price'=>12.34))) ?> Obviously, there would be some caching done so the page content is not rendered everytime. Does this sound good? If not, what would be a good way of doing this? Or is there a project already being developed for doing this? (I'd like to avoid heavy third party libs and something fairly or fully compatible with ZF2 would be nice.) Thanks.

    Read the article

  • Pricing: Meet or Beat?

    - by charles.knapp
    My home dishwasher started making some really interesting noises. I heard radio advertisements from two retailers who promised to meet any competitor's price. Then, I heard another retailer promising that their everyday prices beat their competitors. That got me to thinking about the power of pricing and promotions in the marketing mix (product, price, placement, promotions, and people). What is more powerful to say in a competitive market: your company will meet a similar offer, or your company will beat the others? Will you sell more if you meet or if you beat? I found that the retailer who promised to beat the others really had the best everyday pricing. Even better for me, another retailer had an exclusive promotional sale for long-term customers. Their loyalty promotion beat the best everyday discounter. So, I got the quality and performance I wanted at a tremendous price. So, I have two challenges for marketers. First, where you really have to compete on price as a dominant factor, give people strong reasons to do business with you. If you try to meet other's prices, make the leap to actually beat and not merely meet. Second, upgrade your firm's capabilities where needed. Oracle offers a complete range of great CRM software for loyalty management, marketing promotions, and pricing management that will help you to grow your business.

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >