14

I've decided to get started with MVC 3 and I ran into this issue while trying to redo one of my web apps to MVC3.

I've got projects setup this way:

public class Project
{
    public int      ProjectID       { get; set; }

    [Required(ErrorMessage="A name is required")]
    public string   Name            { get; set; }

    [DisplayName("Team")]
    [Required(ErrorMessage="A team is required")]
    public int      TeamId          { get; set; }

    [DisplayName("Start Date")]
    [Required(ErrorMessage="A Start Date is required")]
    [DisplayFormat(ApplyFormatInEditMode=true, DataFormatString="{0:d}")]
    public DateTime StartDate       { get; set; }

    [DisplayName("End Date")]
    [Required(ErrorMessage="An End Date is required")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
    public DateTime EndDate         { get; set; }
}

And my entry form is written this way for the dates:

<table>
    <tr>
        <td>
            <div class="editor-label">
                @Html.LabelFor(model => model.StartDate)
            </div>
        </td>
        <td>
            <div class="editor-label">
                @Html.LabelFor(model => model.EndDate)
            </div>
        </td>
    </tr>
    <tr>
        <td>
            <div class="editor-field">
                @Html.TextBoxFor(model => model.StartDate, new { @class = "datepicker", id="txtStartDate" })
                @Html.ValidationMessageFor(model => model.StartDate)
            </div>
        </td>
        <td>
            <div class="editor-field">
                @Html.TextBoxFor(model => model.EndDate, new { @class = "datepicker", id = "txtEndDate" })
                @Html.ValidationMessageFor(model => model.EndDate)
            </div>
        </td>
    </tr>
</table>

My problem is that the textbox are now displaying 01/Jan/0001 00:00:00. So first: how can I get the date to be formated to shortdatestring? I've found an MVC2 solution which advised to create an EditorTemplates folder in the SharedFolder and use EditorFor instead but that did not seem to be working with MVC3 . It also seemed to prevent adding classes easily like it is with TextBoxFor

And secondly once that is fixed I've got a special validation system that I need to put in place. I need to have the End Date to be AFTER the Start Date. I'm thinking of doing the check with a javascript i found http://www.datejs.com but is there a way to do the validation directly on my class?

Community
  • 1
  • 1
LanFeusT
  • 2,392
  • 5
  • 38
  • 53

6 Answers6

8

For your edit template try this

@model DateTime?
@Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "datePicker" })

Source: MVC 3 Editor Template with DateTime

jQuery DateTime comparisons

$('#txtbox').change(function() {
            var date = $(this).val();
            var arrDate = date.split("/");
            var today = new Date();
            useDate = new Date(arrDate[2], arrDate[1] -1, arrDate[0]);

            if (useDate > today) {
                alert('Please Enter the correctDate');
                $(this).val('');
            }
        });

Source: Jquery date comparison

Community
  • 1
  • 1
DarkStar33
  • 221
  • 1
  • 4
  • Thanks for links! My dates still show 01/01/001 though. But I guess I can get that re-written in jquery. – LanFeusT Feb 18 '11 at 01:50
  • Might be a stupid question but are the dates populated prior to be sent out to the view? – DarkStar33 Feb 18 '11 at 15:17
  • 1
    I don't see how they could be. My HomeController is pretty straightforward: `public PartialViewResult EntryForm() { ViewBag.Teams = projectDB.Teams.OrderBy(p => p.Name).ToList(); var project = new Project(); return PartialView(project); }` – LanFeusT Feb 18 '11 at 17:38
  • 1
    Try setting the Date as a nullable type, otherwise it will automatically get instantiated to the system default 1/1/0001. http://www.dotnetperls.com/datetime-minvalue – Josh Simerman Sep 15 '11 at 21:39
6

there is a considerably easier way of doing this. Just use a TextBox rather than a TextBoxFor

@Html.TextBox("ReturnDepartureDate", 
    Model.ReturnDepartureDate.ToString("dd/MM/yyyy"))

this has the advantage of adding all the unobtrusive JavaScript elements, etc. Also less code!

Liam
  • 27,717
  • 28
  • 128
  • 190
3

Have a look at this example

@Html.TextBoxFor(s => s.dateofbirth, new { Value = @Model.dateofbirth.ToString("dd/MM/yyyy") })
Irfons
  • 591
  • 4
  • 3
  • It's a little workaround! It creates an second value-attribute. It works only if a capital-V is used. – Dev.Jaap Oct 03 '13 at 13:05
2

If you decorate your viewmodel object with the following you'll only see the date portion within the text box.

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public DateTime Date { get; set; }

Then on your page you can simply do the following

@Html.EditorFor(model => model.Date)

Note that this is using standard MVC3. I don't have a custom Date editor template.

All credit for this answer goes to assign date format with data annotations

Community
  • 1
  • 1
Craig B
  • 333
  • 5
  • 8
1

Too late but might be it can help to someone:

Model:

[Display(Name = "Date of birth")]
public DateTime? DOB{ get; set; }

HTML:

@Html.TextBoxFor(m => m.DOB, "{0:MM/dd/yyyy}", 
          new { @placeholder="MM/DD/YYYY", @au19tocomplete="off" }) 

JavaScript to add the calendar to the control:

$('#DOB').datepicker({changeMonth: true, changeYear: true, 
         minDate: '01/01/1900',  maxDate: new Date});
Ali Adravi
  • 21,707
  • 9
  • 87
  • 85
0

// datimetime displays in the datePicker is 11/24/2011 12:00:00 AM

// you could split this by space and set the value to date only

Script:

    if ($("#StartDate").val() != '') {
        var arrDate = $('#StartDate').val().split(" ");
        $('#StartDate').val(arrDate[0]);
    }

Markup:

    <div class="editor-field">
        @Html.LabelFor(model => model.StartDate, "Start Date")
        @Html.TextBoxFor(model => model.StartDate, new { @class = "date-picker-needed" })
    </div>

Hopes this helps..

coymax
  • 29
  • 1