question

Shri-6058 avatar image
0 Votes"
Shri-6058 asked LanHuang-MSFT commented

MVC checkbox postback and refresh in the dashboard

I have an existing MVC application to read one external database to generate pdf upon submit button and its working fine.
TimeSheet.cshtml – has the following dashboard display:
I was asked to enhance application to insert some checkbox acknowledgement change based on checkbox selection postback on click refresh page. For example, if any day is missing Lunch start/end hour, they will have to select the respective checkbox or voluntarily skip (assuming lunch break was not taken) and submit. Since the application database is external, I don’t have control over that database. I have setup a local database to manage the following checkboxes
SELECT [ID]
,[EmployeeID]
,[Date]
,[MealHours]
,[RestHours]
,[DateCreated]
FROM [TimeSheet].[dbo].[Time]


Basically I need help on the following 3 functionalities:
(1) On click checkbox, postback local database and refresh the page
(2) ExecutePayRollRules logic to assign/call AddTimeEntries and save in local database. Whenever I select the respective week, it should automatically populate the checkbox values on load page.
(3) UI is available I just have to insert with other timesheet rules and add a row and all I need to integrate the values in the dashboard based on number of checkboxes selection. If no selection of checkboxes, no rows.

When any day is selected, the item should be saved in the database and refresh another row stating Lunch Hour (its default 1 hour and can’t change) for the specific date. There is last column called ‘Total’ automatically display ‘5’ if all 5 days checkboxes are selected or ‘2’ if any 2 days checkbox selected and so on. However when each checkbox is selected, the page should be automatically refresh the dashboard. How can I club the postback options with existing timesheet? On clicking missing lunch, I am trying to call this postback on the same Timesheet.cshtml:
@if (Model.TimeSheet.DayList != null)
{
for (var i = 0; i < Model.TimeSheet.DayList.Count(); i++)
{
if((Model.TimeSheet.DayList[i].Total_Worked > 0) && (Model.TimeSheet.DayList[i].Total_Lunch <= 0))
{
@Html.HiddenFor(x => Model.TimeSheet.DayList[i].IslunchBreakAllowed)
<div class="checkbox">
<label>@Html.CheckBoxFor(m => Model.TimeSheet.DayList[i]. IslunchBreakWaived, new { @class = "missed" }) @Html.FormatDayOfTheWeek(Model.TimeSheet.DayList[i].TRAN_DATE) @Html.HiddenFor(x => Model.TimeSheet.DayList[i].TRAN_DATE)</label>
</div>
}
}
}

@section Scripts
{
<script>
$(".missed").click(function () {
$.post("/Home/Calculate", $("form").serialize(), function (json) {
// handle response
// TODO - perform a page refresh/postpack
});
});
}
On clicking, it goes to the following HomeController.cs however I am not able to create a rule/assign & integrate with existing Weekclass. When selected, save the database, when uncheck remove the data and postback option is required. Currently WeekClass timesheet brings all the external data for the week. All I need is I need to save/retrieve data from my local database to include with the timesheet class, so it will display in the dashboard.

public ActionResult Calculate(TimeSheetViewModel model) {
model.TimeSheet.EmployeeID = User.EmployeeID;
// var week = _payRollService.ExecutePayRollRules(model.TimeSheet.Emp_Uno, null, null); // TODO

         _payRollService.AddTimeEntries(model.TimeSheet);

         WeekClass timeSheet = _payRollService.GetTimeSheet(User.EmployeeUno, model.SelectedPayRollWeek, model.tz);   // (.tz is just a timezone that’s working)
         model.TimeSheet = timeSheet;
    

         return View("TimeSheet", model);
     }

Currently _payRollService.AddTimeEntries(model.Timesheet) is null so it won’t save in the database. I need some business logic to add the week first before calling AddTimeEntries

_payRollService.cs has the following for retrieving:

public Time[] GetEntriesFromCustomDb(int emplUno, DateTime fromDate, DateTime toDate)
{
using(var dbContext = new TimeSheetNEEntities())
{
var times = dbContext.Times
.Where(p=> p.EmployeeID == emplUno && (p.Date >= fromDate && p.Date <= toDate)) // TODO - fix, need payroll week
.ToArray();

             return times;
         } 
     }

//Adding or inserting checkbox values and save

public bool AddTimeEntries(WeekClass week)
{
try
{
var times = new List<Time>();
var now = DateTime.UtcNow;

             foreach(var day in week.DayList)
             { 
                 times.Add(new Time
                 { 
                     Date = day.TRAN_DATE,
                     DateCreated = now,
                     EmployeeID = week.Emp_Uno,
                     RestHours = day.Rest_Credit,
                     MealHours = day.Meal_Credit,
                 });
             }

             using(var dbContext = new TimeSheetEntities())
             {
                 dbContext.Times.AddRange(times);  
                 dbContext.SaveChanges();
             }             
         }
         catch(Exception ex)
         {
             // TODO log 
             //throw;
         }   

         return true;
     }
dotnet-aspnet-mvc
· 9
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @Shri-6058,
Is your project asp.net core or asp.net?

Best regards,
Lan Huang

0 Votes 0 ·

Thank you. Its mvc project. not core. I probably want to upgrade near future with core but not immediately as I just need the checkbox functionalities postback refresh and save in local database.
Thanks for any advise or sample code ajax refresh code and fix my database connectivity to save and retrive values.

You can see addTimeEntries, I didnt add the ID but I get the error:

InnerException = {Violation of PRIMARY KEY constraint . Cannot insert duplicate key in object . The duplicate key value is (0).\r\nThe statement has been terminated."}

i probably doing wrong saving the db item.

0 Votes 0 ·

Hi @Shri-6058,

InnerException = {Violation of PRIMARY KEY constraint . Cannot insert duplicate key in object . The duplicate key value is (0).\r\nThe statement has been terminated."}

As the error says, you are trying to insert a record into the table with a key value that already exists in the table. I suggest you take a look at the primary key definition.
About postback you can refer to this code:

Model:

 public class security
     {  
         public long id { get; set; }
         public long user_id { get; set; }
         public long submenu_id { get; set; }
         public long module_id { get; set; }
         public bool flag { get; set; }
         public string module { get; set; }
         public string submenu { get; set; }
     }

View:


   @for(var i = 0; i<Model.Count; i++)
     {
        @Html.HiddenFor(m=>m[i].id)
        <tr class="">    
          <td>    
             @Html.CheckBoxFor(m=>m[i].flag)
          </td>
          <td>@Html.DisplayFor(modelItem => modelItem[i].module) </td>
          <td> @Html.DisplayFor(modelItem => modelItem[i].submenu)</td>
        </tr>
    
 }

Controller


   public ActionResult security(IList<security> model)
             {
                     //each one of the items in your model will have Id an flag property filled with data
             }

Best regards,
Lan Huang

0 Votes 0 ·
Show more comments

1 Answer

Shri-6058 avatar image
0 Votes"
Shri-6058 answered

185299-timesheet.jpg



timesheet.jpg (33.9 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.