Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EditorFor(date): How to display empty text box?

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

How can I make this code display an empty textbox when loaded? Model.date is not nullable, hence always displays a non-empty value. How can I force it to start with an empty value?

Note: I don't want to make it nullable because in the real code, it's tied to a model property which must have a value (BTW, I have a Required data annotation for that property). It doesn't make sense to make it nullable. Replacing it by a default date such as today's is not an option neither because the point in this case is to make sure user doesn't forget to actively specify a date.

TIA.

like image 524
Serge Wautier Avatar asked Nov 29 '10 12:11

Serge Wautier


2 Answers

The problem is if the Model.Date property is not nullable then it will always have a value. In the past I have created an editor template for DateTime (which also utilises the jquery date picker). This allows you to handle your empty value for which you'd presumably be looking out for the date equaling DateTime.MinValue.

So your editor template would look something like:

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

You needn't worry about the empty string for name as this actually gets populated with just the html prefix which should suffice.

This article also describes how to create the editor template.

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

Personally I would have the DateTime in my view model nullable but not on my domain model using the validation in between

like image 162
Mark Avatar answered Sep 20 '22 00:09

Mark


  1. In your model create a sibling property and decorate it with required:

    [Required]
    DateTime? CustomDate {
       get { return date==default(DateTime)?null:date; }
       set { date = value; }
    }
    
  2. In your view replace your input with :

    <%:Html.EditorFor(model => model.CustomDate)%>
    
like image 24
Jorge Goncalves Avatar answered Sep 22 '22 00:09

Jorge Goncalves