我找不到在MVC3中使用JQuery日期選擇器的完整解決方案,並且從我在不同頁面上找到的解決方案中找到了解決方案,但仍然無法正常工作。 我有以下幾點:MVC3中的JQuery日期選擇器奇怪的行爲
型號:
public class Some
{
[Display(Name = "DateCreated", ResourceType = typeof(Resources))]
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "RequiredField")]
[DataType(DataType.Date, ErrorMessage = "Date non valid.")]
[DisplayFormat(NullDisplayText = "NotSpecified", DataFormatString = "{0:dd.MM.yyyy.}")]
public DateTime DateCreated { get; set; }
}
我裝修的財產,因爲我想在客戶端和服務器端驗證和文字。
我使用的這個例子中,家庭控制器和我有:
public ActionResult Index()
{
Some model = new Some { DateCreated = DateTime.Now };
return View(model);
}
[HttpPost]
public ActionResult Index(Some model)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
return View(model);
}
的觀點:
@model TestDatePicker.Models.Some
@using (Html.BeginForm())
{
<div class="editor-label">
@Html.LabelFor(model => model.DateCreated)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.DateCreated)
@Html.ValidationMessageFor(model => model.DateCreated)
</div>
<p>
<input type="submit" value="Save" />
</p>
}
並與DateTime類型渲染領域的自定義模板:
@model Nullable<System.DateTime>
@{
string controlName = ViewData.TemplateInfo.HtmlFieldPrefix;
string controlId = controlName.Replace(".", "_");
if (Model.HasValue) {
@Html.TextBox("", String.Format("{0:dd.MM.yyyy.}", Model.Value), new { @class = "textbox", name = controlName })
}
else {
@Html.TextBox("", String.Format("{0:dd.MM.yyyy.}", DateTime.Now), new { @class = "textbox", name = controlName })
}
}
}
<script type="text/javascript">
$(document).ready(function() {
$(".textbox").datepicker
({
dateFormat: 'dd.mm.yy.',
showStatus: true,
showWeeks: true,
highlightWeek: true,
numberOfMonths: 1,
showAnim: "scale",
showOptions: {
origin: ["top", "left"]
},
onClose: function() {
$(this).valid();
}
});
});
</script>
此代碼發生了什麼? DateTime字段的值將在自定義模板中分配,並顯示爲當天的日期。
- 然而,單擊保存按鈕,在[HttpPost] Index方法我看到模型通過未持有當天日期的價值,但1/1/0001 12:00:00 AM?
- 然後Model.IsValid不會傳遞消息值'26.05.2012'。對於創建的日期無效。 ???對我來說似乎更陌生!
- 顯示上述消息的頁面,而不是我的自定義消息上: [數據類型(DataType.Date,的ErrorMessage =「日期不有效」)
有趣的是,如果你使用的日期選擇器並從中選擇一個數據,您將獲得模型中填充的屬性。而Model.IsValid是TRUE。
這是輸入控件的HTML的樣子:
<input class="textbox" data-val="true" data-val-required="Requred field" id="DateCreated" name="DateCreated" type="text" value="26.05.2012." />
是jQueryUI的日期選擇器不是ASP的最佳選擇。 NET MVC?看來,這個我在網上看到的自定義模板的解決方案,基本的MVC的東西甚至沒有工作?有沒有人知道這樣做的任何完整的教程?我不能成爲面臨這些問題的第一人。
謝謝。
我已經下載了在the blog post大家創建的代碼是指在談論MVC3和日期選擇器,同樣的事情正在發生的事情有什麼時候!
感謝您的回答。請看看我編輯的模板以及我爲id屬性添加的更改。我沒有解決這個問題。 – elector
它的名字,你需要,而不是id(id主要用於JavaScript)。你是否也添加了它? name屬性是http的世界中用來標識表單字段的東西,當它們被引用到thr服務器時。 [這篇文章](http://develoq.net/2011/asp-net-mvc-model-binders-and-how-to-create-custom-model-binder/)解釋了這一點,我相信。 – YavgenyP
感謝這篇文章,這是一個很好的資源。我對該評論投了一票。請查看我的問題中更新的代碼。我認爲,從datepicker中選擇一個值後,頁面的第一次加載需要一些「黑客入侵」的原因。 – elector