【问题标题】:How to update/alter database values using ajax call with out page refresh如何在不刷新页面的情况下使用 ajax 调用更新/更改数据库值
【发布时间】:2017-09-07 17:10:57
【问题描述】:

我是 mvc 的初学者,正在开发一个电子商务网站。 在我的购物车列表中,我需要输入特定数量来计算总价而不刷新页面。 我在 foreach 语句中使用了一个 java 脚本调用,它起作用了,就像当我输入数量并单击“TotalPrice”字段时,价格将自动计算并显示。

但是现在当我点击“TotalPrice”字段时,我需要用新输入的数量和总价更新我的数据库

我正在尝试ajax但不熟悉它

我的看法

                <table class="table">

                        @{
                            int i = 0;

                            foreach (var item in lscart)
                            {
                                i = i + 1;
                                <tr>
                                    <td>@Html.HiddenFor(modelItem => item.CProductID, new { htmlAttributes = new { @class = "form-control", @id = "pid" + @i } })</td>
                                    <td>
                                        @{
                                var base64 = Convert.ToBase64String(item.CImage);
                                var imgSrc = String.Format("data:image/jpg;base64,{0}", base64);
                                <img src='@imgSrc' style="width:100px; height:100px;" />
                                        }
                                    </td>
                                    <td>@Html.DisplayFor(modelItem => item.CProductName)</td>
                                    <td>Rs.</td>
                                    <td>@Html.EditorFor(modelItem => item.CPrice, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly", @id = "cprice" + @i } })</td>

                                    <td>
                                        <div class="col-md-6">

                                            @Html.EditorFor(modelItem => item.Cquantity, new { htmlAttributes = new { @class = "form-control", @placeholder = " Qty", @id = "qt" + @i } })


                                        </div>

                                    </td>


                                    <td>
                                        <div>
                                            @Html.EditorFor(modelItem => item.CTotalPrice, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly", @placeholder = " Total Price", @id = "total" + @i, @onclick = "edValueKeyPress(" + @i + ")", @onkeyup = "edValueKeyPress(" + @i + ")" } })

                                        </div>
                                    </td>

                                    <td><a href="#"><i class="fa fa-close"></i></a></td>
                                </tr>
                            }
                        }


                    </table>

我的 javascript 用于在不刷新页面的情况下计算总价

<script>
    function edValueKeyPress(i) {


        //alert(i);
        var edValue = document.getElementById("qt" + i);
        var edValue1 = document.getElementById("cprice" + i);
        var s = edValue.value * edValue1.value;
        var t = document.getElementById("total" + i);
        t.value = s;

    }
</script>

我的 ajax 代码(这还没有完成,我不知道在我看来在哪里调用这个 ajax 函数)

<script type="text/javascript">

    $(document).ready(function () {
        alert('ready');
        var quantity = document.getElementById("qt" + i);
        var proid = document.getElementById("pid" + i);
        var price = document.getElementById("cprice" + i);
            $.ajax({
                url: '/Products/Cartup',
                type: "GET",
                data: { quantity: quantity, proid: proid, price: price },
                dataType: "JSON",
                success: function (rslt) {

                },
                error: function (rslt) {


                }
            });


    })
    </script>

我的控制器操作方法

 public ActionResult Cartup(int quantity, int proid,float price)
    {
        var Cert = (from cert in db.TBL_Cart where cert.CProductID == proid select cert).FirstOrDefault();
        if (Cert != null)
        {
            int priceint= Convert.ToInt32(price);
            Cert.Cquantity = quantity;
            Cert.CTotalPrice = quantity * priceint;
            db.Entry(Cert).State = EntityState.Modified;
            db.SaveChanges();
        }


        return View();
    }

我的数据库表设计

https://i.stack.imgur.com/mh9F7.png

我使用 db 的完整源代码

https://www.dropbox.com/s/4iegq4kpsoqoue1/backup%20of%20indianhub.zip?dl=0

控制器:产品控制器, 查看:购物车清单

【问题讨论】:

  • 我的视图设计i.stack.imgur.com/HTWvC.png
  • 首先,如果您要更新某些内容,则需要使用“发布”请求。其次,您可以在输入框上创建一个事件侦听器来触发 ajax 调用,或者使用“提交”按钮来推送这些更改。然后只需添加一个点击处理程序。
  • 如果我理解正确,您想在更改 quantity 字段时内联保存您的购物车?
  • 是的,我认为内联可能是技术词
  • 什么是pid 或proid?你从哪里得到的?它没有在你的cshtml中定义

标签: javascript ajax asp.net-mvc


【解决方案1】:

不要添加id,而是为每个td 添加一个唯一的类。例如:

@Html.EditorFor(modelItem => item.Cquantity,
   new { htmlAttributes = new { @class = "quantity form-control", @placeholder = "Qty" } })


然后您可以将change 处理程序附加到quantity 输入。

$(document).ready(function () {
    $(".quantity").change(function () {
        var $tr = $(this).closest("tr"); // get the tr for that row
        var productId = $tr.find('.productID').val(); // get the productID for that row
        var price = $tr.find('.price').val();

        $.ajax({
            url: '/Products/Cartup',
            type: "GET",
            data: { quantity: $(this).val(), proid: productId , price: price },
            dataType: "JSON",
            success: function (data) { alert("success"); },
            error: function (err) { }
        });
    });
});

需要考虑的一些事项:

  • 您的CTotalPrice 是readonly。您不需要将任何关键事件附加到该输入。
  • 不需要给HiddenFor 元素一个td。您可以将其移至价格td
  • db.TBL_Cart where cert.CProductID == proid: 你不应该去CartId 买车吗?我不知道您的数据库结构,但看起来您正在获得第一辆具有特定产品的购物车?不一定是您要更新的购物车。
  • 将cartId、productId 和quantity 发布到服务器。通过控制器中的productId 获取产品价格。用总价更新购物车表
  • 更新表格时应该使用 post 方法

(我希望你把这个作为一个个人项目来学习。因为否则会有很多设计缺陷,你的客户会免费购买所有东西,让你破产:D)

【讨论】:

    【解决方案2】:

    因此,根据您的问题,您想向您的服务器端代码发送一个基于 AJAX 的请求以更新您的数据库,正如我在您的 ajax 代码中看到的那样,您正在 Jquery 中执行 AJAX 请求。

    我不了解 Jquery,但请按照我的简单示例进行基于 AJAX 的请求。

    <body>
        <input type="text" name="quantity" id="totalQuant">
        <input type="text" name="total Amount" id="totalAmt">
        <input type="button" value="TotalPrice" onclick="sendData()">
    </body>
    
    <script>
        var req;
        // initialize request object
        function initReq(){
            if(window.XMLHttpRequest){
                req= new XMLHttpRequest;
            }
            else if(window.ActiveXObject){
                req= new ActiveXObject("Microsoft.XMLHTTP);
            }
        }
    
        //sendData() function defifnation
        function sendData(){
        initReq();
        var amt= document.getElementById("totalAmt").value;
        var qty= document.getElementById("totalQuant").value;
    
        //creat your url // use escape() if you want encode that field
        var url= "yourURL.abc?totalAmt="+escape(amt)+"&totalQuant="+escape(qty);
    
        req.open("GET",url);
    
        // ignore this if you are not sending any response for this request from server
        req.onreadystatechange= processResponse;
    
        req.send();
    
        // example with "POST" type request
        var url= "yourURL.abc"
        req.open("POST",url);
        // add this header if you want encode your fields
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    
        req.send("totalAmt="+amt+"&totalQuant="+qty);
    
        }
    </script>
    

    【讨论】:

      【解决方案3】:

      我只是合并了两个脚本

      <script type="text/javascript">
      function edValueKeyPress(i) {
      
          //debugger;
          //alert(i);
          var edValue = document.getElementById("qt" + i);
          var edValue1 = document.getElementById("cprice" + i);
          var s = edValue.value * edValue1.value;
          var t = document.getElementById("total" + i);
          t.value = s;
      
          var quantity = document.getElementById("qt" + i).value; //alert("quantity" + quantity);
          var proid = document.getElementById("pid" + i).value; //alert(proid);
          var price = document.getElementById("cprice" + i).value; //alert(price);
          //debugger;
          $.ajax({
              async: false,
              cache: false,
              url: '/Products/Cartup',
              type: "GET",
              data: { quantity: quantity, proid: proid, price: price },
              dataType: "JSON",
              success: function (data) { alert("success"); },
              error: function (err) { }
          });
      
      
      }
      </script>
      

      我只是修改了视图中的一些代码

       @{
                                  int i = 0;
      
                                  foreach (var item in lscart)
                                  {
                                      i = i + 1;
                                      <tr>
                                          <td>@Html.TextBoxFor(modelItem => item.CProductID, new {  @style = "display: none", @id = "pid" + @i  })</td>
                                          <td>
      
      ...................rest of the code is same as in the question
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-06
        • 1970-01-01
        • 2015-03-26
        • 2012-04-06
        • 1970-01-01
        相关资源
        最近更新 更多