简体   繁体   English

在 partialview.Net 6 之外更新文本

[英]Update text outside of partialview .Net 6

I have created a table from a list of objects, using a partialview.我使用部分视图从对象列表中创建了一个表。 Using an ajax call(so the page doesnt have to refresh), when a user searchs, filters, etc, it updates the entries in the table(partialview) using a controller method.使用 ajax 调用(因此页面不必刷新),当用户搜索、过滤等时,它使用 controller 方法更新表(部分视图)中的条目。

Outside of the partial view, above the table, there is a "TotalHours" field that shows the total hours of the labor entries that are currently displayed in said table.在部分视图之外,在表格上方,有一个“TotalHours”字段,显示当前显示在所述表格中的人工条目的总小时数。

I was originally using a TempData variable in the controller method to update the "TotalHours" field each time a filter or search was applied, but for some reason, the table didnt refresh with search/filtered entires.我最初在 controller 方法中使用 TempData 变量来在每次应用过滤器或搜索时更新“TotalHours”字段,但由于某种原因,表格没有通过搜索/过滤的整体刷新。 If I remove the TempData variable, the search/filter function I created works perfectly.如果我删除 TempData 变量,我创建的搜索/过滤器 function 可以完美运行。

My question is, what do I need to do to update the "TotalHours" field that is outside the partialview that is being refreshed?我的问题是,我需要做什么来更新正在刷新的局部视图之外的“TotalHours”字段? It is calculated by sum of "Hours" variables in the list of objects that are used in the table.它由表中使用的对象列表中“小时”变量的总和计算得出。

Controller code, with the TempData variable still included even though it doesnt update the partialview in the view: Controller 代码,即使它不更新视图中的部分视图,仍包含 TempData 变量:

[HttpPost]
        public async Task<PartialViewResult> GetRows(Guid? cust, Guid? task, int? workType, int? weekFrom, int? weekTo, int? yearFrom, int? yearTo,
            string startDate = "", string endDate = "", string search = "",string sortName = "", string sortDir = "")
        {
            var model = new List<TimeEntryViewModel>();
            try
            {
                var timeRepo = new TimeRepository(_context);
                var customerRepo = new CustomerRepository(_context);
                var taskRepo = new TaskRepository(_context);
                var user = await _userManager.GetUserAsync(User);
                var entries = await timeRepo.GetTimeEntriesByUserID(user.Id);
                DateTime startWeekYearDate;
                DateTime endWeekYearDate;
                int?[] weekYears = { weekFrom, weekTo, yearFrom, yearTo };

                var entriesFiltered = entries.Where(r => r.CustomerID == cust || cust.Equals(Guid.Empty) || cust == null)
                    .Where(r => r.TaskID == task || cust.Equals(Guid.Empty) || task == null)
                    .Where(r => r.WorkTypeID == workType || workType == null || workType == 0)
                    .ToList();

                if (weekYears.All(x => x.HasValue)) 
                {
                    startWeekYearDate = new DateTime((int)yearFrom, 1, 1);
                    endWeekYearDate = new DateTime((int)yearTo, 1, 1);
                    startWeekYearDate = startWeekYearDate.AddDays(7 * (int)weekFrom).AddDays(-7);
                    endWeekYearDate = endWeekYearDate.AddDays(7 * (int)weekTo);

                    entriesFiltered = entriesFiltered.Where(r => r.Start >= startWeekYearDate)
                        .Where(r => r.End <= endWeekYearDate).ToList();
                }
                if (!string.IsNullOrEmpty(startDate))
                {
                    entriesFiltered = entriesFiltered.Where(r => r.Start >= DateTime.Parse(startDate)).ToList();
                }
                if (!string.IsNullOrEmpty(endDate))
                {
                    entriesFiltered = entriesFiltered.Where(r => r.End <= DateTime.Parse(endDate)).ToList();
                }

                foreach (var entry in entriesFiltered)
                {
                    var entryVm = _mapper.Map<TimeEntryViewModel>(entry);

                    var customer = await customerRepo.GetCustomerByID(entry.CustomerID);
                    var task1 = await taskRepo.GetTaskById(entry.TaskID);
                    entryVm.Customer = customer;
                    entryVm.Task = task1;
                    entryVm.EmployeeName = user.FirstName + " " + user.LastName;
                    entryVm.CustomerName = customer.CustomerName;
                    entryVm.TaskName = task1.Name;

                    model.Add(entryVm);
                }

                if (!string.IsNullOrEmpty(search))
                {
                    model = model.Where(r => r.EmployeeName.Contains(search)
                    || r.CustomerName.Contains(search) || r.TaskName.Contains(search)).ToList();
                }

                model = TimeEntryViewModel.SortList(model, sortName, sortDir);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
            }
            var totalHours = 0.0;
            foreach(var m in model)
            {
                totalHours += m.TotalHours;
            }
            TempData["Total"] = Math.Round(totalHours, 2);


            return PartialView("_entryRows", model);
        } 

PartialView cshtml:部分视图 cshtml:

@using TimeLogger.Core.Enums
@using TimeLogger.ViewModels
@model List<TimeEntryViewModel>

    @foreach(var entry in Model)
            {
                <tr class="customRow">
                    
                    <td>@entry.EmployeeName</td>
                    <td>@entry.Start</td>
                    <td>@entry.End</td>
                    <td>@entry.TotalHours</td>
                    <td>@entry.CustomerName</td>
                    <td>@entry.TaskName</td>
                    <td>@Enum.GetName(typeof(WorkType), entry.WorkTypeID)</td>
                    <td class="text-end">
                        <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown">
                        @*<i class="fa-solid fa-ellipsis-vertical">
                        </i>*@
                        </button>
                        
                        <div class="dropdown-menu" id="dropDownMenu">
                            <a href="javascript:void(0);" class="dropdown-item editEntry"  data-id="@entry.Id">Edit</a>
                            <a href="javascript:void(0);" class="dropdown-item deleteEntry"  data-id="@entry.Id">Delete</a>
                            
                        </div>
                    </td>
                </tr>
            }

View that renders partialview:呈现局部视图的视图:

@using TimeLogger.Core.Enums
@using TimeLogger.ViewModels
@model List<TimeEntryViewModel>
@{
    ViewData["Title"] = "Time Entries";
}


<div id='modal-placeholder' class='modal'>  
    <div class="modal-dialog">  
        <div class="modal-content">  
            <div id='modal-placeholderContent'></div>  
        </div>  
    </div> 
</div>   
<div class="entries">
    <div class="container mt-5 px-2">
    
        <div class="mb-2 d-flex justify-content-between align-items-center">
        
                <div class="position-relative">
                    <span class="position-absolute search"><i id="search" class="fa fa-search modal-custom"></i></span>
                    <input class="form-control w-100" placeholder="" id="searchBox">
                </div>
        <div class="position-relative">
                    <span id="totalHours" class="totalHours">Total Hours: @TempData["Total"]</span>
                </div>
            
            <div class="px-2">
            <button class="btn btn-primary addEntry">Add Entry &nbsp;<i  style="font-size: 1.25rem" class="fa fa-plus-circle fa-2"></i></button>
                <button class="btn filter" onclick="toggleDiv('filters'); return false">Filters &nbsp;<i id="arrow" style="font-size: 1.25rem" class="fa fa-angle-down text-gray-dark bg-light-grey fa-2x"></i></button>
            </div>
        
        </div>
        <div class="container" id="filters" style="display:none">
            <div class="row">
                <div class="col-sm text-white">
                    Customer: @Html.DropDownList("Customers", (IEnumerable<SelectListItem>)ViewBag.Customers, new { @class = "form-control", @id = "customerDropDown" })
                </div>
                <div class="col-sm text-white">
                    Task: @Html.DropDownList("Tasks", (IEnumerable<SelectListItem>)ViewBag.Tasks, new { @class = "form-control", @id = "tasksDropDown" })
                </div>
                <div class="col-sm text-white">
                    Work Type: @Html.DropDownList("WorkTypes", (IEnumerable<SelectListItem>)ViewBag.WorkTypes, new { @class = "form-control", @id = "workTypesDropDown" })
                </div>
            </div>
            <div id="weeksYears">
                <div class="row">
                    <div class="col-sm text-white">
                        From Week: @Html.DropDownList("WeekFrom", (IEnumerable<SelectListItem>)ViewBag.Weeks, new { @class = "form-control", @id = "weekFromDropDown" })
                    </div>
                    <div class="col-sm text-white">
                        To Week: @Html.DropDownList("WeekTo", (IEnumerable<SelectListItem>)ViewBag.Weeks, new { @class = "form-control", @id = "weekToDropDown" })
                    </div>
                    <div class="col-sm text-white">
                        From Year: @Html.DropDownList("YearFrom", (IEnumerable<SelectListItem>)ViewBag.Years, new { @class = "form-control", @id = "yearFromDropDown" })
                    </div>
                    <div class="col-sm text-white">
                        To Year: @Html.DropDownList("YearTo", (IEnumerable<SelectListItem>)ViewBag.Years, new { @class = "form-control", @id = "yearToDropDown" })
                    </div>
                </div>
            </div>
            <div id="dates" style="display: none;">
                <div class="row">
                    <div class="col-sm text-white">
                        <div id="date-picker1" class="md-form md-outline input-with-post-icon datepicker">
                          <label for="startDateFilter">Start Date</label>
                          <i class="fas fa-calendar input-prefix"></i>
                          <input placeholder="Select date" type="text" id="startDateFilter" class="form-control" disabled="disabled">
                        </div>
                    </div>
                    <div class="col-sm text-white">
                        <div id="date-picker2" class="md-form md-outline input-with-post-icon datepicker">
                            <label for="startDateFilter">End Date</label>
                          <i class="fas fa-calendar input-prefix"></i>
                          <input placeholder="Select date" type="text" id="endDateFilter" class="form-control" disabled="disabled">
                        </div>
                    </div>
                </div>
            </div>
            <br/>
            <div class="row">
                <div class="col-sm text-white">
                    <button onclick="filter(); return false" class="btn btn-primary">Filter</button>
                    <button id="dateWeeksToggle" onclick="toggleDatesWeeks(); return false" class="btn btn-info">Filters for Dates</button>
                </div>
                <div class="col-sm text-white">
                    <button onclick="clearFilter(); return false" type="reset" class="btn btn-secondary">Clear Filters</button>
                </div>
            </div>
            <br/>
            <br/>
        </div>
    
        <div class="table-responsive">
            <table class="table table-responsive table-borderless">
                <thead>
                    <tr id="sort-row" class="bg-light">
                        <th id="e" order="desc">Employee</th>
                        <th id="st" order="desc">Start Time</th>
                        <th id="et" order="desc">End Time</th>
                        <th id="h" order="desc">Hours</th>
                        <th id="c" order="desc">Customer</th>
                        <th id="t" order="desc">Task</th>
                        <th id="wt" order="desc">Work Type</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody id="searchFilterResult">
                    @await Html.PartialAsync("_entryRows", Model)
                </tbody>
            </table>
        </div>
    </div>
</div>
    




One easy option that comes to mind would be to add a hidden input to your partial view and set it's value to the Total Count of TempData , then in your ajax use this hidden value to set the one outside of your partial view:想到的一个简单的选择是将隐藏输入添加到您的局部视图并将其值设置为 TempData 的总计数,然后在您的TempData中使用此隐藏值来设置局部视图之外的值:

Partial View :部分视图

....
<input type="hidden" id="hdnhourlytotal" value="@(TempData["total"] ?? 0)" />
@foreach(var entry in Model)
....

ajax : ajax

success: function(data) {
   //add view to DOM
  ....
  //set the element outside of your partial using hidden input
  const totalfromhidden = parseInt(document.getElementById("hdnhourlytotal").value);
  document.getElementById("totalHours").textContent = `Total Hours: ${totalfromhidden}`;
}

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

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