【问题标题】:ASP.NET Multiply in DatalistDatalist 中的 ASP.NET 乘法运算
【发布时间】:2014-03-12 06:33:22
【问题描述】:

我的项目中有一个数据列表,它有两列(“价格”和“数量”)

价格来自数据库。 我正在使用 DropdownList 作为数量。

我想将这两列相乘并动态获得结果。这里的重点是,如果我更改数量,结果必须在不刷新页面的情况下更改。

我该怎么做? 这样做的 datalist 事件是什么?

谢谢。

我的代码

 <asp:DataList ID="DataList1" DataKeyField="SIRANO" runat="server" 
                        onitemcommand="DataList1_ItemCommand"  >

Price:<asp:Label ID="Label5" runat="server" Text='<%#Eval("PRICE") %>'></asp:Label>
Quantity:<asp:DropDownList ID="DropDownList1" runat="server" Height="20px" Width="48px">
   <asp:ListItem>3</asp:ListItem>
  </asp:DropDownList>
<b> Total:<asp:Label ID="Label7" runat="server"></asp:Label></b>

【问题讨论】:

    标签: asp.net dynamic datalist


    【解决方案1】:

    您可能需要编写一个 JavaScript 函数来设置该值。

    DropDownList1.Attributes["onChange"] = "someJavaScriptFunction();";
    DropDownList1.AutoPostBack =False;
    

    参考Client side onchange event for dropdown list

    【讨论】:

      【解决方案2】:

      你最好用javascript来做这个客户端。最简单的方法是使用jQuery。一个优秀的库,让查询和操作 DOM 变得非常容易。

      首先为我们感兴趣的元素添加一些 CSS 类:

      Price:<asp:Label ID="Label5" CssClass="price" runat="server" Text='<%#Eval("PRICE") %>'></asp:Label>
      Quantity:<asp:DropDownList ID="DropDownList1 CssClass="quantity" runat="server" Height="20px" Width="48px">
         <asp:ListItem>3</asp:ListItem>
        </asp:DropDownList>
      <b> Total:<asp:Label ID="Label7" runat="server"  CssClass="label"></asp:Label></b>
      

      Next add the jquery library to your page。然后在里面添加以下内容:

      <script type="text/javascript"  >
           /*Wait until the document is loaded*/
           $(document).ready(function () { 
      
              /*Function to call when drop down with class quantity changes*/
                      $(".quantity").change(function(){  
      
               //Get value from dropdown changed
               var quantity = parseFloat($(this).val()); 
      
               //Get text from sibling element with class price and clean it
               var price = $(this).siblings(".price").html();
               //Clean it
               price = price.replace("$","").replace(",",""); 
               /*Make it a number*/
               price = parseFloat(price);
      
               var total = price * quantity;
      
               /*the b tag is the sibling but we want to update the inner element
               with class total*/
               $(this).siblings("b").children(".total").html("$" +  total); 
      
             });
           }
      </script>
      

      查看运行中的 javascript here

      您可能还希望将输出格式化为货币:How can I format numbers as money in JavaScript?

      【讨论】:

      • 它不工作我如何才能发现问题?我没有得到结果。
      • 查看错误控制台。我还没有实际测试过这个,所以在某些地方可能存在语法错误。如果这不起作用,请在各个点添加 console.log 命令以调试代码。
      • 我修正了几个错别字并添加了一个演示。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-27
      • 1970-01-01
      • 2011-07-21
      • 1970-01-01
      相关资源
      最近更新 更多