2
我的表单中有一个DateTime字段。无论出于何种原因,每次我提交表单时,ModelState都会返回无效状态,并显示一条消息,表明我的日期时间字段(称为PostDate)是必需的,即使在视图模型中我没有设置必需的属性。ModelState中所需的日期时间,但从未设置为
有谁知道为什么会发生这种情况,因为我在圈子里试图弄清楚。
这里是视图模型
public class BlogViewModel
{
[Required]
public string Title { get; set; }
[Required]
public string Content { get; set; }
public bool Published { get; set; }
public DateTime PostDate { get; set; }
}
这里是控制器动作
public ActionResult Create()
{
return View();
}
//
// POST: /Admin/Blog/Create
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(BlogViewModel model)
{
if(ModelState.IsValid)
{
model.Content = HtmlSanitizer.SanitizeHtml(model.Content);
Services.BlogService.CreateBlogPost(model.Title, model.Content, User.Identity.Name);
return RedirectToAction("Index");
}
return View(model);
}
这里是查看
@using Payntbrush.Infrastructure.Mvc.Extensions
@model Payntbrush.Presentation.Demo.MVC3.Areas.Admin.Models.BlogViewModel
@Html.Resource(Html.ScriptTag("Areas/Admin/js/plugins/wysiwyg/jquery.wysiwyg.js"), ResourceType.Js)
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm((string)ViewBag.Action, "Blog", FormMethod.Post, new { Id = "BlogEditor" }))
{
@Html.ValidationSummary(true)
<div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Content)
</div>
<div class="editor-field">
@Html.TextAreaFor(model => model.Content, new { @class = "wysiwyg blog-editor" })
@Html.ValidationMessageFor(model => model.Content)
</div>
<div class="editor-label">
Time of post (Only set this if you want to make a post appear to have been published at a different date.)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.PostDate, new{@class="datetimepicker"})
@Html.ValidationMessageFor(model => model.PostDate)
</div>
<div class="editor-label">
Published (Check to make this post live on the site)
</div>
<div class="editor-field">
@Html.CheckBoxFor(model => model.Published)
@Html.ValidationMessageFor(model => model.Published)
</div>
<p>
<input class="large awesome" type="submit" value="Create" />
@Html.ActionLink("Cancel", "Index", "Blog", null, new { @class = "large awesome cancel-button" })
</p>
}
<div>
</div>
您是否尝试过使用'DateTime?'代替? – bevacqua 2012-03-26 03:47:46
就是这样,谢谢妮可 – Chris 2012-03-26 03:49:27