Hiding the default value for a date

*爱你&永不变心* 提交于 2019-12-20 01:45:41

问题


My View Model:

public partial class FileTransferFilterCriteriaViewModel
{
    public string Fice { get; set; }
    public string SourceEmail { get; set; }
    public string TargetEmail { get; set; }
    public DateTime FromDate { get; set; }
    public DateTime ToDate { get; set; }
    public string Status { get; set; }
    public string Category { get; set; }
}

(Nothing is coming from the DB.)

My Controller:

return View(new FileTransferFilterCriteriaViewModel())

Here is what gets displayed for both FromDate and ToDate:

1/1/0001 12:00:00 AM

My HTML:

@Html.TextBoxFor(x =>x.Criteria.FromDate)

Questions:

  1. If the date is null, how can I suppress the display of the default date value?
  2. If the date is not null, how can I format the date as MM/dd/yyyy?

回答1:


Use nullable date in your ViewModel:

public DateTime? FromDate { get; set; }



回答2:


I have created an editor template and this is working for me.

Changes to view model:

[UIHint(UiHintConstants.DateCalendar)]
        public DateTime? FromDate { get; set; }

        [UIHint(UiHintConstants.DateCalendar)]
        public DateTime? ToDate { get; set; }

After that, created an editor template in Views/Shared/EditorTemplate folder called DateCalendar.chtml:

@using System.Globalization
@model DateTime?

@Html.TextBox("", (Model.HasValue && !Model.Value.ToString(CultureInfo.InvariantCulture).Contains("1900") && !Model.Value.ToString(CultureInfo.InvariantCulture).Contains("0001") ? Model.Value.ToString("MM/dd/yyyy") : string.Empty), new { @class = "datePicker", maxlength = "12", size = "12" })

and then utilized it as:

@Html.EditorFor(x =>x.FromDate)
@Html.EditorFor(x => x.ToDate)

and here is the source code:

<input class="datePicker" id="Criteria_FromDate" maxlength="12" name="Criteria.FromDate" size="12" type="text" value="" />

<input class="datePicker" id="Criteria_ToDate" maxlength="12" name="Criteria.ToDate" size="12" type="text" value="" />

Hope this helps some one else.

I couldn't figure out one part though, moving the size and maxlenth out of the template. In this case it is not relevant but may become in some other instances like where i may lock the text box or don't want the jquery calendar. I'll post as soon as i have a handle on this.




回答3:


Everything is working perfectly. You are not fetching any data from the database though (as evidenced by passing in a newly instantiated view model return View(new FileTransferFilterCriteriaViewModel())). You should consider doing that inside of your controller's action method. To get a shorter date format, use @Html.TextBoxFor(x =>x.Criteria.FromDate.ToShortDateString())



来源:https://stackoverflow.com/questions/12048838/hiding-the-default-value-for-a-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!