简体   繁体   English

通过ajax调用返回部分视图后,再次调用主视图

[英]Main view get called again after a partial view has been returned through ajax call

I have a view which job is to display a list of orders currently stored in the BD. 我有一个视图是要显示当前存储在BD中的订单列表。 It works like this: 它是这样的:

/// <summary>
/// Displays the list of all the suppliers orders filled by now.
/// </summary>
/// <returns></returns>
public ActionResult CheckoutSupplierOrders()
{
    int totalCount;

    List<OrderInfo> listOrders = mOrderManager.ListSupplierOrders(out totalCount);

    Session[CHECKOUT_PAGE_INDEX] = General.CreatePageIndex(totalCount);

    Session[CHECKOUT_PAGE_NUMBER] = 1;

    return View(listOrders);
}

Here's how the view is rendered: 这是呈现视图的方式:

@model List<MagicAdmin2.Models.OrderInfo>

@{
    ViewBag.Title = "Supplier Orders";
}

<script type="text/javascript">
    $(document).ready(function () {
        $('#fetchButton').click(function () {
            alert("clicked!");
            var pageNumber = $('#pageNum').val();
            var sortOrder = $('#sortOrder').val();
            var showOrderType = $('#orderType').val();
            var showOrderDesc = $('#orderDesc').val();
            var showDateCreated = $('#orderCreated').val();
            var showDateCreatedSymbol = $('#orderCreatedSymbol').val();
            var showDateModified = $('#orderModified').val();
            var showDateModifiedSymbol = $('#orderModifiedSymbol').val();

            getNextPage(pageNumber, showOrderType, showOrderDesc, showDateCreated, showDateCreatedSymbol, showDateModified, showDateModifiedSymbol, sortOrder);
        });

        function getNextPage(pageNumber, showOrderType, showOrderDesc, showDateCreated, showDateCreatedSymbol, showDateModified, showDateModifiedSymbol, sortOrder) {
            ShowProgress();
            $.get("@Url.Action("GetSuppliersNextPage", "ManageOrders")", {
                _pageNumber: pageNumber,
                _orderType: showOrderType,
                _orderDesc: showOrderDesc,
                _dateCreated: showDateCreated,
                _dateCreatedSymbol: showDateCreatedSymbol,
                _dateModified: showDateModified,
                _dateModifiedSymbol: showDateModifiedSymbol,
                _sortOrder: sortOrder
            }, function (data) {
                $('#resultsDiv').html(data);
                HideProgress();
            });
        }
    });
</script>

<h2>
    List supplier orders
</h2>

<br/>

@{
    Html.RenderAction("FilterSupplierOrders", "PartialViews");
}

@{
    int pageNumber = (int)Session["checkoutOrderPageNumber"];

    @Html.Hidden("pageNum", pageNumber, new { @id = "pageNum" })
}

<div id="resultsDiv">
    @{
        Html.RenderPartial("CheckoutResultTable", Model);
    }
</div>

The script is there to catch the filters rendered by the @{ Html.RenderAction("FilterSupplierOrders", "PartialViews"); } 该脚本在那里捕获@{ Html.RenderAction("FilterSupplierOrders", "PartialViews"); }渲染的过滤器@{ Html.RenderAction("FilterSupplierOrders", "PartialViews"); } @{ Html.RenderAction("FilterSupplierOrders", "PartialViews"); } line. @{ Html.RenderAction("FilterSupplierOrders", "PartialViews"); }行。 To avoid a missing bug, here's how the filters work: 为避免遗漏错误,过滤器的工作方式如下:

public ActionResult FilterSupplierOrders()
{
    return PartialView("Filters/FilterSuppliersOrders", new SupplierOrdersFilter());
}

And the partial view: 和局部视图:

@model MagicAdmin2.Utility.PageFilters.SupplierOrdersFilter

@using (Html.BeginForm())
{
    <div class="blackBorder defaultBaseStyle">
        <h3 style="background: #efeeef; margin-top: -20px; margin-left: 10px; padding: 0 10px; width: 50px;">Filters</h3>
        Filter by Order Type: @Html.DropDownListFor(_item => _item.OrderType, Model.ListOrderTypes, "All", new { @id = "orderType"})
        Description: @Html.TextBoxFor(_item => _item.Description, new { @id = "orderDesc"})
        Date Created: @Html.DropDownListFor(_item => _item.DateCreatedSymbol, Model.SymbolList, String.Empty, new { @id = "orderCreatedSymbol"}) @Html.TextBoxFor(_item => _item.DateCreated, new { @class = "datePicker", @title = "Choose a date", @id = "orderCreated"})
        Date Modified: @Html.DropDownListFor(_item => _item.DateModifiedSymbol, Model.SymbolList, String.Empty, new { @id = "orderModifiedSymbol"}) @Html.TextBoxFor(_item => _item.DateModified, new { @class = "datePicker", @title = "Choose a date", @id = "orderModified"})
        <input type="submit" value="Fetch" id="fetchButton"/>
    </div>
}

So the reason being that the rest of the view is rendered in the CheckoutResultTable partial view: 因此,原因在于该视图的其余部分在CheckoutResultTable部分视图中呈现:

@using MagicAdmin2.Utility.Data
@model List<MagicAdmin2.Models.OrderInfo>

@if (Model.Count > 0)
{
    @Html.Hidden("sortOrder", Session["checkoutOrderSort"], new { @id = "sortOrder"})

    if (Session["checkoutOrderPagesIndex"] != null)
    {
        <div class="center">
            <span>Pages:</span>
            @{
                List<int> pages = (List<int>)Session["checkoutOrderPagesIndex"];

                int inventoryPageNumber = (int)Session["checkoutOrderPageNumber"];

                if (pages.Count <= 10)
                {
                    foreach (int page in pages)
                    {
                        if (page == inventoryPageNumber)
                        {
                            <span>@page</span>
                        }
                        else
                        {
                            <a href="javascript:void(0)" data-page="@page" class="pageLink">@page</a>    
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < pages.Count; i++)
                    {
                        int pageToShow = pages[i];

                        if (pageToShow == pages[0] || pageToShow == pages[pages.Count - 1])
                        {
                            if (pageToShow == inventoryPageNumber)
                            {
                                <span>@pageToShow</span>
                            }
                            else
                            {
                                <a href="javascript:void(0)" data-page="@pageToShow" class="pageLink">@pageToShow</a>    
                            }
                        }
                        else
                        {
                            if (pageToShow == inventoryPageNumber)
                            {
                                <span>@pageToShow</span>
                            }
                            else if (pages[i] > inventoryPageNumber - 4 && pages[i] < inventoryPageNumber + 5)
                            {
                                <a href="javascript:void(0)" data-page="@pageToShow" class="pageLink">@pageToShow</a>    
                            }
                            else if ((pages[i] == 2 && inventoryPageNumber > 4) || (pages[i] == pages.Count - 1 && inventoryPageNumber < pages.Count - 2))
                            {
                                <span>...</span>
                            }
                        }
                    }
                }
            }
        </div>     
    }
    <table id="resultTable">
        <tr>
            <th>
                ID
            </th>
            <th>
                Date Created
            </th>
            <th>Description</th>
            <th>Date Modified</th>
            <th>
                Type
            </th>
            <th>
                State
            </th>
            <th>Shipping</th>
            <th>Billing</th>
            <th>
                # Items
            </th>
            <th>Prices and charges</th>
            <th>Actions</th>
        </tr>
        @for (int i = 0; i < Model.Count; i++)
        {
            var className = i % 2 == 0 ? "even" : "odd";

            <tr class="@className order orderState-@MagicAdmin2.Utility.Helpers.General.GetEnumDescription(Model[i].mOrderState)">
                <td>@Html.DisplayFor(_item => _item[i].mOrderID)</td>
                <td>@Html.DisplayFor(_item => _item[i].mOrderDateCreated)</td>
                <td class="align-left">@Html.DisplayFor(_item => _item[i].mOrderDescription)</td>
                <td>@(Model[i].mOrderDateModified != null ? Html.DisplayFor(_item => _item[i].mOrderDateModified)
                          : Html.Label(ValueDomain.FIELD_UNAVAILABLE))</td>
                <td>@Html.DisplayFor(_item => _item[i].mOrderType)</td>
                <td>@Html.DisplayFor(_item => _item[i].mOrderState)</td>
                <td class="align-left">
                    Name:        <span class="bold">@Model[i].mShippingFirstName</span><br/>
                    Address:     <span class="bold">@Model[i].mShippingAddress</span><br/>
                    City:        <span class="bold">@Model[i].mShippingCity</span><br/>
                    Country:     <span class="bold">@Model[i].mShippingCountry</span><br/>
                    Region:      <span class="bold">@Model[i].mShippingRegion</span><br/>
                    Postal Code: <span class="bold">@Model[i].mShippingPostalCode</span><br/>
                </td>
                <td class="align-left">
                    Name:        <span class="bold">@Model[i].mBillingLastName</span><br/>
                    Address:     <span class="bold">@Model[i].mBillingAddress</span><br/>
                    City:        <span class="bold">@Model[i].mBillingCity</span><br/>
                    Country:     <span class="bold">@Model[i].mBillingCountry</span><br/>
                    Region:      <span class="bold">@Model[i].mBillingRegion</span><br/>
                    Postal Code: <span class="bold">@Model[i].mBillingPostalCode</span><br/>
                </td>
                <td>@Model[i].mOrderItemCount</td>
                <td id="priceField" class="align-left adjustedField">
                    Detail Amount: <span class="bold">@Html.DisplayFor(_item => _item[i].mOrderDetailAmount) $</span><br/>
                    Taxes:         <span class="bold">@Html.DisplayFor(_item => _item[i].mOrderTaxes) $</span><br/>
                    Shipping Cost: <span class="bold">@Html.DisplayFor(_item => _item[i].mOrderShippingCost) $</span><br/>
                    Handling Cost: <span class="bold">@Html.DisplayFor(_item => _item[i].mOrderHandlingCost) $</span><br/>
                    @Html.ActionLink("Item Total", "DisplaySupplierOrdersToCheckout", new { @_sortOrder = ViewBag.TotalSortParm } ):    <span class="bold">@Html.DisplayFor(_item => _item[i].mOrderTotal) $</span><br/>
                </td>
                <td>@Html.ActionLink("Confirm reception", "SelectOrder", new { _orderID = Model[i].mOrderID })</td>
            </tr>
        }
    </table>
    if (Session["checkoutOrderPagesIndex"] != null)
    {
        <div class="center">
            <span>Pages:</span>
            @{
                List<int> pages = (List<int>)Session["checkoutOrderPagesIndex"];

                int inventoryPageNumber = (int)Session["checkoutOrderPageNumber"];

                if (pages.Count <= 10)
                {
                    foreach (int page in pages)
                    {
                        if (page == inventoryPageNumber)
                        {
                            <span>@page</span>
                        }
                        else
                        {
                            <a href="javascript:void(0)" data-page="@page" class="pageLink">@page</a>    
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < pages.Count; i++)
                    {
                        int pageToShow = pages[i];

                        if (pageToShow == pages[0] || pageToShow == pages[pages.Count - 1])
                        {
                            if (pageToShow == inventoryPageNumber)
                            {
                                <span>@pageToShow</span>
                            }
                            else
                            {
                                <a href="javascript:void(0)" data-page="@pageToShow" class="pageLink">@pageToShow</a>    
                            }
                        }
                        else
                        {
                            if (pageToShow == inventoryPageNumber)
                            {
                                <span>@pageToShow</span>
                            }
                            else if (pages[i] > inventoryPageNumber - 4 && pages[i] < inventoryPageNumber + 5)
                            {
                                <a href="javascript:void(0)" data-page="@pageToShow" class="pageLink">@pageToShow</a>    
                            }
                            else if ((pages[i] == 2 && inventoryPageNumber > 4) || (pages[i] == pages.Count - 1 && inventoryPageNumber < pages.Count - 2))
                            {
                                <span>...</span>
                            }
                        }
                    }
                }
            }
        </div>     
    }
}
else
{
    <span class="errorMessage">There are no orders to checkout.</span>
}

is because if the use at that moment choose to filter the obtained data, say, by name, he may, using a jquery method that calls the controller method: 这是因为如果当时用户选择按名称过滤所获得的数据,那么他可以使用调用控制器方法的jquery方法进行过滤:

public PartialViewResult GetSuppliersNextPage(int _pageNumber, string _orderType, string _orderDesc, string _dateCreated, string _dateCreatedSymbol,
                                            string _dateModified, string _dateModifiedSymbol, string _sortOrder)
{
    int totalCount;

    string sortOrder;

    if (Session[CHECKOUT_SORT_ORDER] == null)
    {
        sortOrder = _sortOrder;

        Session[CHECKOUT_SORT_ORDER] = _sortOrder;
    }
    else
    {
        sortOrder = (string)Session[CHECKOUT_SORT_ORDER];

        switch (_sortOrder)
        {
            default:
                sortOrder = _sortOrder;
                break;
        }
    }

    ISupplierOrderParams filterParams = new SupplierOrderParams(_pageNumber, _orderType, _orderDesc, _dateCreated, _dateCreatedSymbol, _dateModified, _dateModifiedSymbol, sortOrder);

    List<OrderInfo> listItems = mOrderManager.ListSupplierOrdersNextPage(filterParams, out totalCount);

    Session[CHECKOUT_PAGE_INDEX] = General.CreatePageIndex(totalCount);

    Session[CHECKOUT_PAGE_NUMBER] = _pageNumber;

    return PartialView("CheckoutResultTable", listItems);
}

My main trouble is that the method is called appropriately and does it rendering. 我的主要麻烦是该方法被正确调用并进行渲染。 However right after the rendering of the partial view is done, the CheckoutSupplierOrders() controller method is called (WHY?!?), thus destroying the purpose of the ajax call. 但是,在完成部分视图的渲染之后, CheckoutSupplierOrders()调用CheckoutSupplierOrders()控制器方法(WHY?!?),从而破坏了ajax调用的目的。 And I don't know why this occurs. 而且我不知道为什么会这样。

Looks like the problem is that the button, when clicked, not only triggers the load of the partial view, but also submits the form. 看起来问题在于按钮被单击时,不仅触发了局部视图的加载,而且还提交了表单。 After the form is submitted and the response from server is received (response being the same page), browser renders this response and you see exactly the same page you are on. 提交表单并接收到来自服务器的响应(响应是同一页面)后,浏览器将呈现此响应,您将看到与您所在页面完全相同的页面。

To avoid such behavior, prevent it in the click handler: 为了避免这种行为,请在点击处理程序中防止出现这种情况:

$('#fetchButton').click(function (e) {
    e.preventDefault();

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

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