我有这样的模特。基本上我有一个类名字段和两个字段的开始和结束日期格式为MM / dd / yyyy
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的那天,我都会收到验证错误。
你知道为什么或我在这里做错了吗?
非常感谢你。
答案 0 :(得分:0)
在您的网络配置文件中添加区域性:
<system.web>
<globalization uiCulture="en" culture="en-GB"/>
并在全局asax中添加以下内容:
protected void Application_BeginRequest(object sender, EventArgs e)
{
CultureInfo culture = new CultureInfo("en-GB");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
希望获得帮助。
答案 1 :(得分:-2)
将[DataType(DataType.Date)]
添加到注释中。