简体   繁体   English

重新加载网页未按预期工作 asp.net MVC

[英]Reload webpage not working as intended asp.net MVC

I need to delete a row from a list that is dynamic on click of a button, in order to do so I have used jquery to find the row index of the list, after doing this I use ajax to send the row index to a controller action where I delete the row from the list, this all works fine it is then supposed to reload the page as to show that the row has been deleted.我需要从单击按钮时动态的列表中删除一行,为此我使用 jquery 来查找列表的行索引,这样做后我使用 ajax 将行索引发送到 Z5904C1083F2C03E我从列表中删除该行的操作,这一切正常,然后应该重新加载页面以显示该行已被删除。 However my reload page function isn't working properly, it never reloads the page on the first try but after I reload the page manually once it starts working for all subsequent deletes.但是,我的重新加载页面 function 无法正常工作,它不会在第一次尝试时重新加载页面,但在我手动重新加载页面后,一旦它开始为所有后续删除工作。 I honestly have no idea why it is doing this.老实说,我不知道为什么要这样做。

Jquery and html: Jquery 和 html:

<table cellpadding="0" cellspacing="0" border="0">
            <tbody>
                @foreach (var item in Model)
                {
                    <tr>
                        <td>@item.Name</td>
                        <td>@item.Quantity</td>
                        <td>@item.Price</td>
                        <td>@item.Total</td>
                        <td><button>delete</button></td>
                    </tr>
                }
            </tbody>
        </table>

<script type="text/javascript">
    $("table tr button").on('click', function () {
        var rowIndex = $(this).closest('td').parent()[0].sectionRowIndex;
        var f = {};
            f.url = '@Url.Action("RemoveFromCart", "Cart")';
            f.type = "POST";
            f.datatype = "json";
            f.data = JSON.stringify({ RowId: rowIndex });
            f.contentType = "application/json";
            $.ajax(f);
            window.location.reload(true);
    });
</script>

Code in controller: controller 中的代码:

        [HttpPost]
        public ActionResult RemoveFromCart(int RowId)
        {
            HomeController.cart.RemoveAt(RowId);
            return RedirectToAction("Cart");
        }

Wrap your jQuery event within a $(document).ready() method.将您的 jQuery 事件包装在$(document).ready()方法中。 You jQuery event is getting attached even before the DOM elements has loaded on the (ie Delete buttons on the rows) the page.您的 jQuery 事件甚至在 DOM 元素加载到页面上(即行上的删除按钮)之前就已附加。 Document ready will wait till the page has loaded completely and then attach 'click' event to the delete buttons.文档就绪将等待页面完全加载,然后将“单击”事件附加到删除按钮。

$(document).ready(function() {
    $("table tr button").on('click', function () {
        var rowIndex = $(this).closest('td').parent()[0].sectionRowIndex;
        var f = {};
            f.url = '@Url.Action("RemoveFromCart", "Cart")';
            f.type = "POST";
            f.datatype = "json";
            f.data = JSON.stringify({ RowId: rowIndex });
            f.contentType = "application/json";
            $.ajax(f);
            window.location.reload(true);
    });
});

May be you want to more dynamic on page without reload page.可能是您想在页面上更加动态而无需重新加载页面。 First you need add to model of cart property Id .首先,您需要添加到购物车属性Id的 model 。

And use this simple code:并使用这个简单的代码:

    /// <summary>
    /// Model from post request
    /// </summary>
    public class ModelCart
    {
        public string Id { get; set; }
    }


[HttpPost]
        public ActionResult RemoveFromCart([FromBody] ModelCart cartInfo)
        {
            // Need to delete from cart by id
            //HomeController.cart.RemoveAt(cartInfo);
            HomeController.cart.Remove(items.FirstOrDefault(x => x.Id == cartInfo.Id));
            return RedirectToAction("Cart");
        }

In html:在 html 中:

 <table cellpadding="0" cellspacing="0" border="0">
        <tbody>
            @foreach (var item in Model.Items)
            {
                <tr>
                    <td>@item.Name</td>
                    <td>@item.Quantity</td>
                    <td>@item.Price</td>
                    <td>@item.Total</td>
                    <td><button data-id="@item.Id">delete</button></td>
                </tr>
            }
        </tbody>
    </table>

    <script type="text/javascript">
        jQuery(document).ready(function () {
            $("table tr button").on('click',
                function () {
                    // Find id wich need to delete
                    var id = $(this).attr('data-id');

                    // Find element that will be delete after success response from server
                    var trObj = $(this).closest('tr');

                    $.ajax({
                        url: '@Url.Action("Reload", "Home")',
                        type: 'POST',
                        data: JSON.stringify({ id: id }),
                        dataType: "json",
                        contentType: "application/json",
                        success: function () {
                            // catch success respone and delete element
                            trObj.remove();
                        }
                    });
                });
        });
    </script>

If you need to reload page, i think you don't need to use ajax, just send post request.如果您需要重新加载页面,我认为您不需要使用 ajax,只需发送帖子请求即可。 It is more simple and understanding.它更简单和理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM