C# 将模型返回到视图
我正在做一个类似这样的项目: 当我输入所有字段并选择要报告时间的日期时。 如果出现错误,例如小时数不正确,我希望返回相同的视图,这样用户就不需要再次输入所有内容 它有点有效,“Beskrivning”和“Timmar:”会用发送它的值填充回来,但我选择的日期不是 这是我的模型:C# 将模型返回到视图,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,我正在做一个类似这样的项目: 当我输入所有字段并选择要报告时间的日期时。 如果出现错误,例如小时数不正确,我希望返回相同的视图,这样用户就不需要再次输入所有内容 它有点有效,“Beskrivning”和“Timmar:”会用发送它的值填充回来,但我选择的日期不是 这是我的模型: public class NewTimeReportModel { public TimeReportTimes Times; public List<Project> Projec
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;
}
}
公共类NewTimeReportModel
{
公共时间报告时报;
公开项目清单;
公共Guid?报告ID;
公共日期时间日期;
公共图书馆;
公共词典
{
获取{return Projects.ToDictionary(x=>x.ProjectId,x=>x.Hours);}
}
公共NewTimeReportModel()
{
项目=新列表();
}
公共NewTimeReportModel(报告)
{
ReportId=report.TimeReportID;
项目=新列表();
foreach(report.TimeReportProjects中的var projectData)
{
添加(新项目)
{
Description=projectData.Description,
小时=项目数据。小时,
ProjectId=projectData.FK\u ProjectId
});
}
Times=新的TimeReportTimes(report.TimeReportDatas.Single());
NoTimeToReport=report.NoTimeToReport;
日期=报告日期;
}
公共类项目
{
公共Guid项目ID{get;set;}
公共字符串说明{get;set;}
公共双小时{get;set;}
公共布尔设置小时数(字符串小时数)
{
双重价值;
尝试
{
if(string.IsNullOrEmpty(小时))
{
值=-1;
}
else if(小时数包含(“:”)
{
字符串[]vals=hours.Split(“:”);
value=double.Parse(vals[0])+new TimeSpan(0,int.Parse(vals[1]),0).TotalHours;
}
else if(小时数,包含(“,”)
{
值=double.Parse(小时);
}
否则如果(!double.TryParse(小时,输出值))
{
返回false;
}
}
抓住
{
返回false;
}
小时=价值;
返回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();
}
public ActionResult时间报告(FormCollection表单、Guid?id、bool?noTimeToReport)
{
展示项目(真实);
NewTimeReportModel projectData=新NewTimeReportModel();
//删除时间报告
if(form!=null&&form.AllKeys.Contains(“删除”))
{
新建DatabaseLayer().DeleteTimeReport(Guid.Parse(form[“ReportId”]);
加载默认设置(项目数据);
ViewData.Model=projectData;
ViewData[“已删除”]=true;
返回操作(“索引”);
}
//更新时间报告
if(id.HasValue&(form==null | | form.AllKeys.Length==0))
{
使用(DatabaseLayer db=newdatabaselayer())
{
var timeReport=db.GetTimeReport(id.Value);
projectData=新的NewTimeReportModel(timeReport);
}
}
//加载默认设置
else if(form==null | | form.AllKeys.Length==0)
{
加载默认设置(项目数据);
}
其他的
{
//获取视图中的所有日期,并将其格式化为yy mm dd,以便我们可以将其解析为日期时间。
列表日期=格式化日期(表格[“日期]);
//循环所有日期并将日期保存到数据库。
projectData=报告日期(表单、projectData、日期、noTimeToReport);
if(ModelState.IsValid)
{
//如果到目前为止,一切正常,我们将时间报告保存到数据库中
projectData.SaveToDatabase(Constants.CurrentUser(User.Identity.Name));
ViewData[“已发布”]=true;
projectData=新的NewTimeReportModel();
}
else if(projectData.Projects.Count==1)
{
ListAllMssingDays();
ViewData.Model=projectData;
返回视图(projectData);
}
//如果报告了所有日期,则加载默认设置。
加载默认设置(项目数据);
}
//获取并列出所有缺失的天数
ListAllMssingDays();
ViewData.Model=projectData;
返回视图();
}
以下是我在视图中选择日期的方式:
<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');
}
});
});
//选择单独的日期
$(文档).ready(函数(){
$('input[name=“isoDate”]”)。更改(函数(){
$(“#日期”).val(“”);
$('input[name=“isoDate”]”)。每个(函数(){
如果(选中此项){
$(“#date”).val($(“#date”).val()+“”+$(this.val());
}
});
});
});
//选择月份内的所有日期
$(函数(){
$(“.selectAll”)。在(“单击”上,函数(){
如果($(this).is(':checked')){
if($(this).closest('.panel default')。长度>0)
$(this).closest('.panel default').find('input[name='isoDate']).prop('checked',this.checked);
其他的
$(“输入[name='isoDate']”)prop('checked',this.checked);
$('input[name=“isoDate”]”)。触发器('change');
}否则{
if($(this).closest('.panel default')。长度>0)
$(this).closest('.panel default').find(“input[name='isoDate']”)prop('checked',false);
其他的
$(“输入[name='isoDate']”)prop('checked',false);
$('input[name=“isoDate”]”)。触发器('change');
}
});
});
这是我的v
<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>