0

在我的 EditorTemplates 中,我有 DateTime.cshtml - 它可以在创建/编辑/更新视图中找到:

@model Nullable<System.DateTime> 

@if ( Model.HasValue ) { 
   @Html.TextBox( "" , String.Format( "{0:dd/MM/yyyy}" , Model.Value ) , new  { @class = "datepicker span2" } ) 
} 
else { 
   @Html.TextBox( "" , String.Format( "{0:dd/MM/yyyy}" , DateTime.Now ) , new { @class = "datepicker span2" } ) 
} 

创建搜索视图时,我还想使用日期时间选择器 - 当视图未链接到模型而只是纯 HTML 时,我将如何使用上面的代码对视图进行编码?

如果我只是在 Razor 标记中输入以下内容:

@using (Html.BeginForm())
{
    <p>
        Availability between: @Html.TextBox( "From" , String.Format( "{0:dd/MM/yyyy}") , new  { @class = "datepicker span2" } ) 
                         and: @Html.TextBox( "To" , String.Format( "{0:dd/MM/yyyy}") , new  { @class = "datepicker span2" } )
        <input type="submit" value="Search" /></p>
}

我只是得到错误:

{"Index (zero based) must be greater than or equal to zero and less than the size of the argument list."}

谢谢你的帮助,

标记

4

2 回答 2

1

你没有DateTimeString.Format- 这就是你得到那个错误的原因,它需要一个参数,但你没有提供任何参数。尝试使用DateTime.Now

例如

@Html.TextBox( "From" , String.Format( "{0:dd/MM/yyyy}", DateTime.Now ), 
new  { @class = "datepicker span2" } ) 

或者,只需将两个DateTime属性添加到您的 ViewModel,并EditorFor在它们上使用帮助程序。

于 2012-07-02T00:06:05.010 回答
0

不要TextBox在主视图中使用。如果您希望您的自定义编辑器模板呈现您应该使用EditorFor帮助器:

@using (Html.BeginForm())
{
    <p>
        Availability between: 
        @Html.EditorFor(x => x.From)
        and: 
        @Html.EditorFor(x => x.To)

        <input type="submit" value="Search" />
    </p>
}

如果FromTo属性的类型为DateTime,则 ASP.NET MVC 将自动呈现您的自定义编辑器模板 ( ~/Views/Shared/EditorTemplates/DateTime.cshtml)。

于 2012-07-02T06:05:13.827 回答