简体   繁体   English

为什么Ajax.BeginForm在局部视图之前再次加载索引?

[英]Why does Ajax.BeginForm load index again before partialview?

I am using Ajax.BeginForm to update a div with a partialview (loading logs based on the search input in the search fields). 我正在使用Ajax.BeginForm用PartialView更新div(根据搜索字段中的搜索输入加载日志)。

The general idea is to load the Index the first time you log in with default values and then only update the log (partial view) when you search from there on. 通常的想法是,第一次使用默认值登录时加载索引,然后仅从该位置搜索时才更新日志(部分视图)。

The problem - When I debug my program it stops at Index in the controller before loading the partial view - resulting in long loading times. 问题 -调试程序时,它在加载部分视图之前在控制器的Index处停止-导致加载时间长。

The question - How can I make the Ajax request only load the partial view? 问题 -如何使Ajax请求仅加载部分视图?


Code

_LogLayout.cshtml _LogLayout.cshtml

 <div id="log" class="tab">
     <h1>Log</h1>

     @using (Ajax.BeginForm("LogPartialView", "LogModelsController",
         new AjaxOptions
         {
             HttpMethod = "POST",
             InsertionMode = InsertionMode.Replace,
             UpdateTargetId = "divLogs",
         }, new
         {
             id = "NewTableId"
         }))
         {
             <p>@Html.TextBox("SearchString", null, new { @placeholder = "Message" })</p>
             if (Roles.IsUserInRole(WebSecurity.CurrentUserName, "Admin"))
             {
                 <p>
                     @Html.DropDownList("SelectedCustomer", Model.LogModelVmObject.CustomerList, new { @id = "logdropdownlabel", @class = "dropdownlabels" })
                 </p>
             }

             <p>
                 <input type="submit" class="standardbutton logsearch" name="submit" value="Search" />
             </p>
         }

         @using (Html.BeginForm("ExportData", "LogModels"))
         {
             <input type="submit" name="export" class="standardbutton export" value="Export to Excel" />
         }

         <div id="divLogs">
             @Html.Raw(ViewBag.Data)
             @Html.Partial("_LogPartialLayout")
         </div>
     </div>
</div>

LogModelsController.cs LogModelsController.cs

/// <returns>   
///     Returns the populated log with the current customers information if the user is of the Role Member,     
///     otherwise if the user is in the Role Admin - then show all customers logs by default.
/// </returns>
public async Task<ActionResult> Index()
{
    if (Session["myID"] == null)
        return ExpireSession();

    const int pageNumber = 1;
    var lmvm = new LogModelVm { CurrentSort = null };
    var myId = Convert.ToInt32(Session["myID"].ToString());

    if (Roles.IsUserInRole(WebSecurity.CurrentUserName, "Admin"))
    {
        _customer = _cdvdb.GetAllCustomerIds();
        _message = _db.GetLogs();
    }
    else if (Roles.IsUserInRole(WebSecurity.CurrentUserName, "Member"))
    {
        _message = _db.GetLogsById(myId);
    }

    var logs = _message.OrderByDescending(i => i.Timestamp).ToPagedList(pageNumber, PageSize);

    if (Roles.IsUserInRole(WebSecurity.CurrentUserName, "Admin"))
    {
        if (_customer != null)
        {
            var selectListItems = _customer as SelectListItem[] ?? _customer.ToArray();
            foreach (var log in logs)
                log.Name = selectListItems.FirstOrDefault(a => a.Value == log.CustomerId.ToString())?.Text;
            lmvm.CustomerList = selectListItems;
        }
    }

    lmvm.Logs = logs;

    var model = new LogStatisticsModel
    {
        LogModelObject = new LogModel(),
        StatisticsModel = await StatisticsData.GetAllCurrentStatisticsValues(1, DateTime.Now),
        LogModelVmObject = lmvm
    };

    return View(model);
}

/// <returns> 
///     Returns a partial view of the log. 
/// </returns>
[HttpPost]
public ActionResult LogPartialView(string searchString, int? selectedCustomer, string currentMessageFilter, string currentCustomerFilter, int? page, string sortOrder)
{
    // Some code.
    return PartialView("_LogPartialLayout", model);
}

RouteConfig.cs RouteConfig.cs

using System.Web.Mvc;
using System.Web.Routing;

namespace MyProject
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Login", action = "Index", id = UrlParameter.Optional });

            routes.MapRoute("Log", "{controller}/{action}/{Id}");

            routes.MapRoute("Admin", "");
        }
    }
}

Index.cshtml Index.cshtml

@model MyProject.Models.LogStatisticsModel
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />

@{
    ViewBag.Title = "MyPortal";
    Layout = "~/Views/Shared/_LogLayout.cshtml";
}

After a long discussion with @StephenMuecke which (among a ton of useful things) told me to try and comment out every single javascript in the _LogLayout.cshtml file and one by one uncomment them back and see if any of them caused the problem. 在与@StephenMuecke进行了长时间的讨论之后(其中有很多有用的内容),我告诉我尝试注释掉_LogLayout.cshtml文件中的每个javascript,然后逐个取消注释,看看是否有任何问题引起了问题。

I found that the following script caused the problem. 我发现以下脚本导致了问题。

<script type="text/javascript">
    $('#loadercheck').click(function () 
    {
        $('#loader').show();
        $.ajax(
        {
            success: function () 
            {
                $('#loader').delay(1200).hide(400);
            }
        });
    })
</script>

The following script was used to display a spinning loader while the log was loading data. 在日志加载数据时,以下脚本用于显示旋转加载器。 Apparently this caused the Index() to be called again. 显然,这导致Index()再次被调用。 So I will have to find a new way to display a loader now... 所以我现在必须找到一种新的方式来显示装载机...

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

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