Adding a search form using a DateTime template

2019-08-30 13:40发布

In my EditorTemplates, I have DateTime.cshtml - which works find in create/edit/update views:

@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" } ) 
} 

When creating a search view, I also want to use a datetime picker - how would I code the view use the code above, when it's not linked to a model, but just plain HTML?

If I just enter the following into my Razor markup:

@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>
}

I just get the error:

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

Thanks for any help,

Mark

2条回答
三岁会撩人
2楼-- · 2019-08-30 14:08

You haven't specified a DateTime in the String.Format - that is why you are getting that error, it expects one parameter, but you haven't supplied any. Try using DateTime.Now

e.g.

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

Alternatively, just add two DateTime properties to your ViewModel, and use the EditorFor helper on them.

查看更多
一纸荒年 Trace。
3楼-- · 2019-08-30 14:25

Don't use TextBox inside your main view. If you want your custom editor template to render you should use the EditorFor helper:

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

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

If the From and To properties are of type DateTime, then ASP.NET MVC will wutomatically render your custom editor template (~/Views/Shared/EditorTemplates/DateTime.cshtml).

查看更多
登录 后发表回答