如何遍历文本框的值,然后使用ajax将其发送到控制器? [英] How to iterate through values of text boxes ,and send them to controller using ajax?

查看:89
本文介绍了如何遍历文本框的值,然后使用ajax将其发送到控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用asp.net mvc在购物车上工作.我已经完成了购物车的全部功能,用户可以在其中通过文本框删除产品或更新其数量.但是我不喜欢在购物车中每个产品的右侧有2个额外链接的部分(更新数量并删除产品).我对删除产品链接很满意,因为对每个产品都具有删除链接是有意义的.现在,我只希望有一个按钮或链接称为保存更改".在单击该按钮/链接时,我想从每个数量文本框中收集值,将其传递给控制器​​,并执行需要执行的操作,然后从控制器作为json对象返回.问题是,到目前为止,我仅使用ajax几天,并且不知道如何从视图中的文本框中迭代/收集值并将其发送到控制器.

I am working on shopping cart using asp.net mvc .I have made complete functionality of shopping cart where user can remove product or update its quantity via text box. But i don't like the part where i have 2 extra links on the right side of each product in cart (update quantity and remove product).I am fine with remove product links cos it makes sense to have remove link for each product. Now i want to have only one button or link called save changes. On click on that button/link i want to gather values from each quantity text box ,pass it to controller and do what its need to be done and return as json object from controller. Problem is that i use ajax for few days only so far and don't know how to iterate/gather values from text boxes in my view and send them to controller.

这是我的购物车的外观.

这是我的观点

@model OnlineShop.ViewModels.ShopingCartViewModel
....
<p class="button">
    @Html.ActionLink("Checkout >>", "AddressAndPayment", "Checkout")
</p>

    <table class="table-bordered">
    <tr>
        headers
    </tr>

    @for (int i = 0; i < Model.CartItems.Count; i++)
    {


        <tr id="row-@Model.CartItems[i].RecordID">
            <td>
                <img src="@Url.Content(Model.CartItems[i].Product.ProductImg)" class="img-responsive" style="width:60px;height:60px;padding:5px;"/>
            </td>
            @*need to be done later*@ 
            <td>

                @Html.ActionLink(Model.CartItems[i].Product.ProductName, "Details", "Store", new{id =Model.CartItems[i].ProductID}, null) 
            </td>
            <td>
                @Model.CartItems[i].Product.ProductPrice
            </td>
            <td>
                @Html.TextBoxFor(model=>model.CartItems[i].CartCount,new { style="width:60px;text-align:center;"})
            </td>
            <td>
                <a href="#" class="UpdateLink" data-id="@Model.CartItems[i].RecordID" txt-id="CartItems_@(i)__CartCount">
                    Update Quantity

                </a>&nbsp;|&nbsp;
            </td>
            <td>
                <a href="#" class="RemoveLink" data-id="@Model.CartItems[i].RecordID">
                    Remove from
                    cart
                </a>
            </td>
        </tr>


    }

    <tr>
        <td>
        </td>
        <td></td>
        <td></td>
        <td></td>
        <td align="center"> <b>Total</b></td>

        <td id="cart-total" align="center">
           <b> @Model.CartTotal</b>
        </td>
    </tr>
</table>
</div>

脚本

@section scripts {
<script type="text/javascript">
    $(function () {
        // Document.ready -> link up remove event handler
        $(".RemoveLink").click(function () {
            // Get the id from the link
            var recordToDelete = $(this).attr("data-id");
            if (recordToDelete != '') {
                // Perform the ajax post
                $.post("/ShopingCart/RemoveFromCart", { "id": recordToDelete }, function (data) {
                    // Successful requests get here
                    // Update the page elements
                    if (data.ItemCount == 0) {
                        $('#row-' + data.DeleteID).fadeOut('slow');
                    } else {
                        $('#item-count-' + data.DeleteID).text(data.ItemCount);
                    }
                    $('#cart-total').text(data.CartTotal);
                    $('#update-message').text(data.Message);
                    $('#cart-status').text('Cart (' + data.CartCount + ')');
                });
            }
        });
    });
    $(function () {
        // Document.ready -> link up remove event handler
        $(".UpdateLink").click(function () {
            // Get the id from the link
            var recordToUpdate = $(this).attr("data-id");
            var countToUpdate=$("#" + $(this).attr("txt-id")).val();
            if (recordToUpdate != '') {
                // Perform the ajax post
                $.post("/ShopingCart/UpdateCartQuantity", { "id": recordToUpdate, "cartCount": countToUpdate}, function (data) {
                    // Successful requests get here
                    // Update the page elements
                    if (data.ItemCount == 0) {
                        $('#row-' + data.DeleteID).fadeOut('slow');
                    } else {
                        $('#item-count-' + data.DeleteID).text(data.ItemCount);
                    }
                    $('#cart-total').text(data.CartTotal);
                    $('#update-message').text(data.Message);
                    $('#cart-status').text('Cart (' + data.CartCount + ')');
                });
            }
        });
    });
    function handleUpdate() {
        // Load and deserialize the returned JSON data
        var json = context.get_data();
        var data = Sys.Serialization.JavaScriptSerializer.deserialize(json);
        // Update the page elements
        if (data.ItemCount == 0) {
            $('#row-' + data.DeleteID).fadeOut('slow');
        } else {
            $('#item-count-' + data.DeleteID).text(data.ItemCount);
        }
        $('#cart-total').text(data.CartTotal);
        $('#update-message').text(data.Message);
        $('#cart-status').text('Cart (' + data.CartCount + ')');
    }
</script>
}

感谢您的辛苦工作,但这使我更加困惑:) ...我将尽力更好地解释我要实现的目标...这是我的控制器方法

Thank you for hard work,but that confuses me even more :) ...I'll try to explain better what i am trying to achieve ...this is my controller method

[HttpPost]
        public ActionResult UpdateCartQuantity(int id , int cartCount)
        {
            var cart = ShopingCart.GetCart(this.HttpContext);

            string productName = storeDB.Carts.Single(
                item => item.RecordID == id).Product.ProductName;

            Product product = storeDB.Carts.Single(
                item => item.RecordID == id).Product;

            int oldCount = (int)storeDB.Carts.Single(
                item => item.RecordID == id).CartCount;

            int itemCount = 0;
            if (oldCount==cartCount)
            {
                itemCount = oldCount;
            }
            else if (cartCount>oldCount)
            {
                itemCount = oldCount;
                int sub = cartCount-oldCount;
                for (int i = 0; i < sub; i++)
                {
                    cart.AddToCart(product);
                    itemCount++;
                }
            }
            else
            {

                itemCount = (int)cart.UpdateCartCount(id, cartCount);

            }
            var results = new ShopingCartRemoveViewModel
            {
                Message = Server.HtmlEncode(productName) +
                " has quantity updated.",
                CartTotal = cart.GetTotal(),
                CartCount = (int)cart.GetCount(),
                ItemCount = itemCount,
                DeleteID = id
            };


            return Json(results);
        }

所以我在看一些教程,并考虑使用<input type="text">字段而不是@html.TextBoxFor(model=>model.CartItems[i].CartCount)$ajax()来仅发布每个<input>中的recordID和值...唯一的名称/ID或类,但考虑到我有CartItems列表,因此我需要使用for语句为每个Cartitem动态创建<input>数量字段.因此,当用户按下save changes按钮时,它需要从每个输入字段读取值并进行处理方法UpdateCartQuantity以及recordID.对我来说,主要问题是如何动态处理<input>的类/标识,以便每个都有唯一的标识,以及如何读取/发送该recordID和输入值.另外,我现在对视图进行了一些编辑,而不是像您看到的foreach一样.

So i was looking at some tutorials and thinking to use <input type="text"> field instead of @html.TextBoxFor(model=>model.CartItems[i].CartCount) and $ajax() to post only recordID and value from each <input> ...I could do that maybe for one cartitem with unique name/id or class but considering that i have list of CartItems i need to dynamically make <input> quantity fields with for statement for each cartitem .So when user press save changes button it needs to read values from each input field and process with method UpdateCartQuantity along with recordID. Main problem for me is how to deal with classes/id's of that <input> dynamically so each has unique id and how to read/send that recordID and input value. Also i edited my view a bit now i have for statement instead of foreach like u can see.

推荐答案

仅此而已.有更好的方法,但这会给您一个想法.

Just a guess thats all. there r better ways but this will give u an idea.

public class Product
    {
        //unique
        public int Id
        {
            get;
            set;
        }
        public String Name
        {
            get;
            set;
        }
        public Decimal Price
        {
            get;
            set;
        }
        public Int32 Quantity
        {
            get;
            set;
        }

        public Decimal SubTotal
        {
            get
            {
                return Price * Quantity;
            }
        }

    }

public class ProductList
    {
        public List<Product> productList = new List<Product>
        {
            new Product{Id=1, Name="Product 1", Quantity=4, Price=100},
            new Product{Id=2,Name="Product 2", Quantity=3, Price=200},
            new Product{Id=3,Name="Product 3", Quantity=2, Price=300},
            new Product{Id=4,Name="Product 4", Quantity=1, Price=400}
        };

        public Decimal Total
        {
            get
            {
                Decimal total = 0M;
                foreach( var item in productList )
                {
                    total += item. SubTotal;
                }

                return total;
            }
        }

    }
    <script type="text/javascript">
        function UpdateSubANdTotal(price, quantity, subid) {
            $(subid).html($(quantity).html() * $(price).prop("value"));

            var elems = document.getElementsByClassName('subtotal');
            var tTotal = 0;
            for (var i = 0; i < elems.length; i++) {
                if (typeof elems[i].innerHTML !== null) {
                    tTotal = Number(tTotal) + Number(elems[i].innerHTML);
                }
            }
            $('#ABTotal').text(tTotal);

//因为您已更新页面,上面的代码. //在此处进行ajax调用,以使用产品ID和数量更新行数据库.因为产品数量是唯一的.返回一个int或boolean以显示给已更新的用户(如果有).您的ajax调用操作应接受productid数量.如果需要,请发送一些用户凭据,如果不需要它的帖子.

//as u have updated page, above code. // do an ajax call here to update your db of row with product id and quantity. as product quantity is unique. return an int or boolean for display to user of updated if any. your ajax calling action should accept productid quantity. if needed send some user credentials, if its post not needed.

  1. 焦点输出页面上的内容会自动更新.
  2. 一个ajax调用,以使用信息更新购物车数据库.
  3. 显示更新为用户.
  4. 如果用户点击提交.采取行动将处理购物车中的物品并继续进行结帐...
  5. 如果您希望ajax调用可以在用户每次进行更改时发送整个列表(购物车项),那么您的选择...

上面的代码,应该没问题.

code above and it should be okay.

        }
    </script>

    <div class="">
        @foreach( var item in Model.productList )
        {
            String priceId = "M" + item.Id.ToString();
            String subTotId = "S" + item.Id.ToString();
            String QuanId = "Q" + item. Id. ToString();

            <div class="">
                <label >@item.Name</label>
                <input name="pname[]" id="@priceId" type="text" value="@item.Price" onblur="UpdateSubANdTotal(@priceId, @QuanId, @subTotId)" />
                <label id="@QuanId">@item.Quantity</label>
                <label class="subtotal"  id="@subTotId">@item.SubTotal</label>
            </div>
        }
    </div>

    <label id="ABTotal">@Model.Total</label>

请给我发布校验码,如果可以的话,我想看看.希望此代码块可以.

give me post check code, if u can , i will like to take a look. hope this code block is ok.

这篇关于如何遍历文本框的值,然后使用ajax将其发送到控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆