Home > OS >  Update text outside of partialview .Net 6
Update text outside of partialview .Net 6

Time:08-06

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.

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.

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. If I remove the TempData variable, the search/filter function I created works perfectly.

My question is, what do I need to do to update the "TotalHours" field that is outside the partialview that is being refreshed? 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:

[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:

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

    @foreach(var entry in Model)
            {
                <tr >
                    
                    <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 >
                        <button  type="button" id="dropdownMenuButton" data-toggle="dropdown">
                        @*<i >
                        </i>*@
                        </button>
                        
                        <div  id="dropDownMenu">
                            <a href="javascript:void(0);"   data-id="@entry.Id">Edit</a>
                            <a href="javascript:void(0);"   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 >  
        <div >  
            <div id='modal-placeholderContent'></div>  
        </div>  
    </div> 
</div>   
<div >
    <div >
    
        <div >
        
                <div >
                    <span ><i id="search" ></i></span>
                    <input  placeholder="" id="searchBox">
                </div>
        <div >
                    <span id="totalHours" >Total Hours: @TempData["Total"]</span>
                </div>
            
            <div >
            <button >Add Entry &nbsp;<i  style="font-size: 1.25rem" ></i></button>
                <button  onclick="toggleDiv('filters'); return false">Filters &nbsp;<i id="arrow" style="font-size: 1.25rem" ></i></button>
            </div>
        
        </div>
        <div  id="filters" style="display:none">
            <div >
                <div >
                    Customer: @Html.DropDownList("Customers", (IEnumerable<SelectListItem>)ViewBag.Customers, new { @class = "form-control", @id = "customerDropDown" })
                </div>
                <div >
                    Task: @Html.DropDownList("Tasks", (IEnumerable<SelectListItem>)ViewBag.Tasks, new { @class = "form-control", @id = "tasksDropDown" })
                </div>
                <div >
                    Work Type: @Html.DropDownList("WorkTypes", (IEnumerable<SelectListItem>)ViewBag.WorkTypes, new { @class = "form-control", @id = "workTypesDropDown" })
                </div>
            </div>
            <div id="weeksYears">
                <div >
                    <div >
                        From Week: @Html.DropDownList("WeekFrom", (IEnumerable<SelectListItem>)ViewBag.Weeks, new { @class = "form-control", @id = "weekFromDropDown" })
                    </div>
                    <div >
                        To Week: @Html.DropDownList("WeekTo", (IEnumerable<SelectListItem>)ViewBag.Weeks, new { @class = "form-control", @id = "weekToDropDown" })
                    </div>
                    <div >
                        From Year: @Html.DropDownList("YearFrom", (IEnumerable<SelectListItem>)ViewBag.Years, new { @class = "form-control", @id = "yearFromDropDown" })
                    </div>
                    <div >
                        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 >
                    <div >
                        <div id="date-picker1" >
                          <label for="startDateFilter">Start Date</label>
                          <i ></i>
                          <input placeholder="Select date" type="text" id="startDateFilter"  disabled="disabled">
                        </div>
                    </div>
                    <div >
                        <div id="date-picker2" >
                            <label for="startDateFilter">End Date</label>
                          <i ></i>
                          <input placeholder="Select date" type="text" id="endDateFilter"  disabled="disabled">
                        </div>
                    </div>
                </div>
            </div>
            <br/>
            <div >
                <div >
                    <button onclick="filter(); return false" >Filter</button>
                    <button id="dateWeeksToggle" onclick="toggleDatesWeeks(); return false" >Filters for Dates</button>
                </div>
                <div >
                    <button onclick="clearFilter(); return false" type="reset" >Clear Filters</button>
                </div>
            </div>
            <br/>
            <br/>
        </div>
    
        <div >
            <table >
                <thead>
                    <tr id="sort-row" >
                        <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>
    




CodePudding user response:

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:

Partial View:

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

ajax:

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