如何为此代码添加日期选择器:
<fieldset>
<legend>Search criteria</legend>
@Html.Label("StartDate", "Start Date:")
@Html.TextBox("StartDate")
@Html.Label("enddate", "End Date:")
@Html.TextBox("enddate")
<input type="submit" value="Apply" />
</fieldset>
我想为startdate显示一个日期选择器,为结束日期显示一个。
谢谢
答案 0 :(得分:13)
Html 5解决方案
如果您打算使用HTML 5,您只需在输入上指定一个类型,如下所示:
@Html.TextBox("StartDate", Model.StartDate, new { @class = "datepicker", @type="date" })
哪会呈现日期控件:
JQuery UI解决方案
你也可以使用Jquery UI:
<fieldset>
<legend>Search criteria</legend>
@Html.Label("StartDate", "Start Date:")
@Html.TextBox("StartDate", string.Empty, new { @class = "datepicker" })
@Html.Label("enddate", "End Date:")
@Html.TextBox("enddate", string.Empty, new { @class = "datepicker" })
<input type="submit" value="Apply" />
</fieldset>
<script>
$(function() {
$( ".datepicker" ).datepicker();
});
</script>
上面为TextBox添加了一个datepicker
类,然后运行javascript来装饰它们。
http://jqueryui.com/datepicker/
请注意我已经坚持使用Textbox,但我会使用TextBoxFor。
<强>更新强>
请参阅下面的工作示例。
答案 1 :(得分:4)
MVC有一个内置类datefield
,在进入该字段后,将打开一个允许他们选择日期的模块。
<fieldset>
<legend>Search criteria</legend>
@Html.LabelFor( model => Model.StartDate, "Start Date:")
@Html.TextBoxFor( model => Model.StartDate, new {@class = "datefield"})
@Html.LabelFor( model => Model.EndDate, "End Date:")
@Html.TextBoxFor( model => Model.EndDate, new {@class = "datefield"})
<input type="submit" value="Apply" />
</fieldset>
那应该解决它。
有人提到使用datepicker
通过JQueryUI
,但datefield
是我认为在微软的MVC中原生支持的东西
答案 2 :(得分:1)
正如Hutchonoid所说的那样。如果要进行模型链接,可以使用TextBoxFor执行以下操作:
@Html.TextBoxFor(model => model.StartDate, new { @class="datefield", @type="date" })
将传入的HTML属性对象中的类型作为第二个参数包含在TextBoxFor中非常重要,否则它将不会创建日期的输入类型,它将保留为文本框。
希望这可以帮助别人。 : - )
答案 3 :(得分:0)
<fieldset>
<legend>Search criteria</legend>
@Html.Label("StartDate", "Start Date:")
@Html.TextBox("StartDate", string.Empty, new { @class = "datepicker" })
@Html.Label("enddate", "End Date: enter code here")
@Html.TextBox("enddate", string.Empty, new { @class = "datepicker" })
<input type="submit" value="Apply" />
</fieldset>
<script>
$(function() {
$( ".datepicker" ).datepicker();
});
</script>
那应该解决它。
答案 4 :(得分:0)
这是对我有用的代码:
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/jqueryui")
@Styles.Render("~/Content/themes/base/css")
<script type="text/javascript">
$(document).ready(function () {
$("#Dob").datepicker({
changeMonth: true,
changeYear: true
});
});
</script>
}