我有这样的模型。基本上,我有一个类名和字段在MM/DD/YYYY的格式两个字段的开始和结束日期为什么我的DateTime ModelState无效?
namespace WebApplication3.Models
{
public class DateTimeViewModel
{
public DateTimeViewModel()
{
StartDate = new DateTime(DateTime.Today.Year, 1, 1);
EndDate = new DateTime(StartDate.Year, 12, 31);
}
public int Id { get; set; }
public string ClassName { get; set; }
[Display(Name = "Start Date")]
[Required(ErrorMessage = "{0} is required")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }
[Display(Name = "End Date")]
[Required(ErrorMessage = "{0} is required")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime EndDate { get; set; }
}
}
这是我的看法
@model WebApplication3.Models.DateTimeViewModel
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>DateTimeViewModel</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.ClassName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ClassName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ClassName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.StartDate, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.StartDate, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.StartDate, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.EndDate, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.EndDate, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.EndDate, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
这是我HttpPost
控制器
[HttpPost]
public ActionResult Create(WebApplication3.Models.DateTimeViewModel model)
{
if(ModelState.IsValid)
{
/// do something
}
return View();
}
我现在遇到的问题是,当我进入了一天就像在下面的图片我ModelState.IsValid被返回FALSE:
看起来每次我进入一个大于12的日子时,我都会得到验证错误。
你知道我为什么或在做什么错在这里吗?
非常感谢。
@Jasen:不正确。 OP有'ApplyFormatInEditMode = true'这意味着modelbinder将使用指定的日期格式来解析返回的字符串日期。 –
我在这里看不到任何明显的错误。你确定你已经重建了你的解决方案,因为应用了'DisplayFormat'?在支持'datetime'输入类型(EditorFor'将使用)的浏览器中,你会碰到这个问题,因为值需要采用ISO格式(YYYY-MM-DD),但是如果有的话浏览器确实支持这种输入类型,并且在这里似乎不是问题,因为不存在该字段的自定义控件。 –
@克里斯是的我重建了一个跑了同样的错误。从我所看到的情况来看,验证失败是因为它认为月份是一天而一天是月份。我只是不知道如何解决它。我现在正在做的事情是,在我的控制器中删除ModelState.IsValid检查,我知道这是不好的做法。我希望修正:( – CB4