mardi 25 août 2015

asp.net c# Controller acting weird

First of, the name of this question is not very good but I could not think of a better one. I'm working a project where I report hours perday, and on diffrent projects.

This is how it looks like. enter image description here

But the problem is now, if I would submit it it would end up like this.

enter image description here

Like we can see here on the summary of the month, that on the secound date it duplicates the project and shows it up twice, this happends if I add more dates as well. But it never happends on the first date.

I've been debugging it, but I do not see any diffrent behavior from when it were ran the first time, all the values are the same etc.

This is the controller

public ActionResult TimeReport(FormCollection form, Guid? id)
    {
        ViewDataDictionary vd = new ViewDataDictionary
        {
            ["projects"] = new DatabaseLayer().GetConsultantProjects(Constants.CurrentUser(User.Identity.Name)),
            ["id"] = 1,
            ["showDescription"] = true
        };
        ViewData["vd"] = vd;

        NewTimeReportModel projectData = new NewTimeReportModel();

        if (form != null && form.AllKeys.Contains("delete"))
        {
            new DatabaseLayer().DeleteTimeReport(Guid.Parse(form["ReportId"]));
            LoadDefaultSettings(projectData);
            ViewData.Model = projectData;
            return View();
        }

        if (id.HasValue && (form == null || form.AllKeys.Length == 0))
        {
            using (DatabaseLayer db = new DatabaseLayer())
            {
                var timeReport = db.GetTimeReport(id.Value);
                projectData = new NewTimeReportModel(timeReport);
                if (projectData.Projects.Count == 1)
                    projectData.Projects[0].Hours = null;
            }
        }
        else if (form == null || form.AllKeys.Length == 0)
        {
            LoadDefaultSettings(projectData);
        }
        else
        {
            //Takes all the dates that is being sent from the view and put into a string.
            string input = (form["date"]);
            input = input.Trim();
            string[] dates = input.Split(' ');

            //Foreach to loop over all the dates, also rebuilds the string to look like yy-mm-dd so we can parse it to a datetime
            foreach (string result in dates.Select(date => date.Substring(0, 2) + '-' + date.Substring(2, 2) + "-" + date.Substring(4, 2)))
            {
                DateTime reportDate;
                if (!DateTime.TryParse(result, out reportDate))
                {
                    ModelState.AddModelError("Date", "Felaktikt datum");
                }

                var projectNumbers = (from x in form.AllKeys
                    where x.Contains("_")
                    select x.Substring(x.IndexOf('_'))).Distinct();

                projectData.Times = new TimeReportTimes(form["startTime"], form["endTime"], form["breakTime"], ModelState);
                projectData.Date = reportDate;

                //Checks to see if we did choose a project.
                var enumerable = projectNumbers as string[] ?? projectNumbers.ToArray();
                if (!enumerable.Any())
                {
                    ModelState.AddModelError("Projekt", "Inga projekt valda...");
                }
                else
                {
                    int emptyHours = 0;

                    foreach (string projectNumber in enumerable)
                    {

                        projectData.Projects.Add(new NewTimeReportModel.Project
                        {
                            Description = form["description" + projectNumber],
                            Hours = null,
                            ProjectId = Guid.Parse(form["project" + projectNumber])
                        });

                        string hourString = form["hours" + projectNumber];
                        if (string.IsNullOrEmpty(hourString))
                        {
                            emptyHours++;
                            projectData.Projects[projectData.Projects.Count - 1].Hours =
                                projectData.Times.WorkedHours;
                        }
                        else
                        {
                            if (!projectData.Projects[projectData.Projects.Count - 1].SetHours(hourString))
                            {
                                ModelState.AddModelError("hours_" + projectNumber, "Felaktig antal timmar");
                            }
                        }
                    }
                    //Checks so the hours are right.
                    if (emptyHours > 1 || (emptyHours == 0 && projectData.Projects.Sum(x => x.Hours) != projectData.Times.WorkedHours))
                    {
                        ModelState.AddModelError("hours_" + enumerable.First(),
                            "Antalet timmar stämmer ej överrens");
                    }

                    //Checks so the worked hours is bigger than 0
                    if (projectData.Projects.Any(x => x.Hours <= 0))
                    {
                        ModelState.AddModelError("hours_" + enumerable.First(),
                            "Antalet timmar måste vara större än noll");
                    }

                    if (!string.IsNullOrEmpty(form["ReportId"]))
                    { 
                        projectData.ReportId = Guid.Parse(form["ReportId"]);
                    }

                    if (ModelState.IsValid)
                    {
                        //saves the report to the database
                        projectData.SaveToDatabase(Constants.CurrentUser(User.Identity.Name));
                        //Saves ViewData To true so we know in the view it's been posted.
                        ViewData["posted"] = true;

                        projectData = new NewTimeReportModel();
                        LoadDefaultSettings(projectData);
                    }
                    else if (projectData.Projects.Count == 1)
                    { 
                        projectData.Projects[0].Hours = null;
                    }
                }
            }
        }

        var missingdays = new DatabaseLayer().GetConsultantMissingDays(Constants.CurrentUser(User.Identity.Name));
        if (missingdays.Count == 0)
        {
        }
        else
        {
            ViewBag.MissingDays = missingdays;
        }

        ViewData.Model = projectData;

        return View();
    }

Aucun commentaire:

Enregistrer un commentaire