EditorFor (date): How to display an empty text field?

<%: Html.EditorFor(model => model.date)%>

How can I get this code to display an empty text box at boot time? Model.date is not NULL, so a non-empty value is always displayed. How to make it start with an empty value?

Note. I do not want it to be null, because in real code it is bound to a model property that should have a value (BTW, I have data annotation Requiredfor this property). It makes no sense to make it null. Replacing it with a default date, such as today, is not an option either because in this case you need to make sure that the user does not forget to actively indicate the date.

TIA.

+5
source share
5

, Model.Date null, . DateTime ( jquery date picker). , , , , DateTime.MinValue.

, :

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime>" %>
<%=Html.TextBox("", (Model != DateTime.MinValue ? Model : string.Empty)) %>

, html, .

, .

http://geekswithblogs.net/michelotti/archive/2010/02/05/mvc-2-editor-template-with-datetime.aspx

DateTime , ,

+8
  • sibling :

    [Required]
    DateTime? CustomDate {
       get { return date==default(DateTime)?null:date; }
       set { date = value; }
    }
    
  • :

    <%:Html.EditorFor(model => model.CustomDate)%>
    
+2

<td> <div>, id jquery.

<script type="text/javascript">
$(document).ready(function(){
$("#clearme").html("");
});
</script>

<div id="clearme">
<%: Html.EditorFor(model => model.date)%>
</div>

, MVC, .

- , , , .

0

:

public DateTime DOB { get; set; } 
[Required]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
public DateTime? NullableDOB
{
  get => DOB.ToNullable();
  set => DOB = value.DefaultIfNull(); 
}

ToNullible(), DefaultIfNull() IsNull() - :

public static T? ToNullable<T>(this T source) where T : struct
  => source.IsNull(default(T)) ? (T?)null : source;

public static T? ToNullable<T>(this T source, T @default) where T : struct
  => source.IsNull(@default) ? (T?)null : source;

public static T DefaultIfNull<T>(this T? source, T @default) where T : struct
  => source ?? @default;

public static T DefaultIfNull<T>(this T? source) where T : struct
  => DefaultIfNull(source, default(T));


public static bool IsNull<T>(this T source) where T : struct
  => source.Equals(default(T));
0

jquery.

I solve my problem as follows:

        @if(Model.HolidayDate <= DateTime.MinValue)
        {
            @Html.TextBoxFor(model => model.HolidayDate, new { @class = "datepick", @style = "width: 75px;", @id="dataInput"})
        }
        else
        {
            @Html.TextBoxFor(model => model.HolidayDate, new { @class = "datepick", @style = "width: 75px;"})
        }

and at the end of the page:

    $ (function () {$ ('# DataInput') Val ('');});
-1
source

All Articles