返回模型查看

时间:2015-09-23 07:58:34

标签: c# asp.net asp.net-mvc

我正在开发一个看起来像这样的项目: enter image description here

当我输入所有字段时,我选择要报告时间的日期。 如果出现错误,例如小时数不正确,我想返回相同的视图,这样用户就不需要再次输入所有内容。

它有点工作,“Beskrivning”和“Timmar:”用所发送的值填充,但我选择的日期不是。

这是我的模特:

    public class NewTimeReportModel
{
    public TimeReportTimes Times;
    public List<Project> Projects;
    public Guid? ReportId;
    public DateTime Date;
    public bool NoTimeToReport;
    public Dictionary<Guid, double?> ProjectDictionary
    {
        get { return Projects.ToDictionary(x => x.ProjectId, x => x.Hours); }
    }
    public NewTimeReportModel()
    {
        Projects = new List<Project>();
    }
    public NewTimeReportModel(Report report)
    {
        ReportId = report.TimeReportID;
        Projects = new List<Project>();
        foreach (var projectData in report.TimeReportProjects)
        {
            Projects.Add(new Project
            {
                Description = projectData.Description,
                Hours = projectData.Hours,
                ProjectId = projectData.FK_ProjectID
            });
        }

        Times = new TimeReportTimes(report.TimeReportDatas.Single());
        NoTimeToReport = report.NoTimeToReport;
        Date = report.Date;
    }
    public class Project
    {
        public Guid ProjectId { get; set; }
        public string Description { get; set; }
        public double? Hours { get; set; }
        public bool SetHours(string hours)
        {
            double value;
            try
            {
                if (string.IsNullOrEmpty(hours))
                {
                    value = -1;
                }
                else if (hours.Contains(":"))
                {
                    string[] vals = hours.Split(':');
                    value = double.Parse(vals[0]) + new TimeSpan(0, int.Parse(vals[1]), 0).TotalHours;
                }
                else if (hours.Contains(","))
                {
                    value = double.Parse(hours);
                }
                else if (!double.TryParse(hours, out value))
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }

            Hours = value;
            return true;
        }
    }

这是我的控制器,我将返回视图。

    public ActionResult TimeReport(FormCollection form, Guid? id, bool? noTimeToReport)
    {
        ShowProjects(true);

        NewTimeReportModel projectData = new NewTimeReportModel();

        //Deletes Timereport
        if (form != null && form.AllKeys.Contains("delete"))
        {
            new DatabaseLayer().DeleteTimeReport(Guid.Parse(form["ReportId"]));
            LoadDefaultSettings(projectData);
            ViewData.Model = projectData;
            ViewData["deleted"] = true;
            return RedirectToAction("Index");
        }

        //Update Timereport
        if (id.HasValue && (form == null || form.AllKeys.Length == 0))
        {
            using (DatabaseLayer db = new DatabaseLayer())
            {
                var timeReport = db.GetTimeReport(id.Value);
                projectData = new NewTimeReportModel(timeReport);
            }
        }
        //Loads default settings
        else if (form == null || form.AllKeys.Length == 0)
        {
            LoadDefaultSettings(projectData);
        }
        else
        {
            //Get's all the dates from the view and formates them to look like yy-mm-dd so we can parse it to a datetime.
            List<string> dates = FormateDate(form["date"]);
            //Loops over all the dates and saves the dates to the database.
            projectData = ReportDates(form, projectData, dates, noTimeToReport);

            if (ModelState.IsValid)
            {
                //If we get this far everything is ok and we save the timereport to the database
                projectData.SaveToDatabase(Constants.CurrentUser(User.Identity.Name));
                ViewData["posted"] = true;
                projectData = new NewTimeReportModel();
            }
            else if (projectData.Projects.Count == 1)
            {
                ListAllMssingDays();
                ViewData.Model = projectData;
                return View(projectData);
            }

            //Loads default settings if all dates been reported.
            LoadDefaultSettings(projectData);
        }
        //Get's and lists all the missing days
        ListAllMssingDays();
        ViewData.Model = projectData;
        return View();
    }

这就是我在观点上选择日期的方式:

<script type="text/javascript" language="javascript">
//Select seperate date
$(document).ready(function() {
    $('input[name="isoDate"]').change(function() {
        $("#date").val("");
        $('input[name="isoDate"]').each(function() {
            if (this.checked) {
                $("#date").val($("#date").val() + " " + $(this).val());
            }
        });
    });
});

//Select all dates inside the month
$(function () {
    $(".selectAll").on("click", function () {
        if ($(this).is(':checked')) {
            if($(this).closest('.panel-default').length > 0)
                $(this).closest('.panel-default').find("input[name='isoDate']").prop('checked', this.checked);
            else
                $("input[name='isoDate']").prop('checked', this.checked);
            $('input[name="isoDate"]').trigger('change');
        } else {
            if($(this).closest('.panel-default').length > 0)
                $(this).closest('.panel-default').find("input[name='isoDate']").prop('checked', false);
            else
                $("input[name='isoDate']").prop('checked', false);
            $('input[name="isoDate"]').trigger('change');
        }
    });
});

这是我的观点:

<div class="portlet-body form">
                                    <div class="form-group">
                                        <label class="col-md-5">Ingen tid att rapportera</label>
                                        @Html.CheckBoxFor(model => model.NoTimeToReport, new { @id = "check" })
                                    </div>
                                    @if (Model.ReportId.HasValue)
                                    {
                                        <div class="form-group">
                                            <label class="col-md-4 control-label">Redigera datum:</label>
                                            <div class="col-md-5">
                                                @Html.TextBox("date", Model.Date.ToShortDateString(), new { @class = "form-control", @readonly = "true" })
                                            </div>
                                        </div>
                                    }
                                    <div class="form-group">
                                        <label class="col-md-4 control-label">Start tid:</label>
                                        <div class="col-md-5">
                                            @Html.TextBox("startTime", Model.Times.StartTime, new { @class = "form-control timepicker timepicker-24" })
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-md-4 control-label">Slut tid:</label>
                                        <div class="col-md-5">
                                            @Html.TextBox("endTime", Model.Times.EndTime, new { @class = "form-control timepicker timepicker-24" })
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-md-4 control-label">Rast Längd:</label>
                                        <div class="col-md-5">
                                            @Html.TextBox("breakTime", Model.Times.BreakTime, new { @class = "form-control timepicker timepicker-24" })
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-md-4 control-label">Tid jobbad:</label>
                                        <div class="col-md-5">
                                            @Html.TextBox("workedHours", Model.Times.WorkedHours, new { @class = "form-control", @disabled = "" })
                                        </div>
                                    </div>
                                </div>

1 个答案:

答案 0 :(得分:0)

当您检查该用户条目无效时,请返回已实施模型的视图,以便它再次绑定到视图。return View(projectData);