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