3

I want to Edit date as "23/5/2017" and time as "03:53 PM". my model has Date DisplayFormat as "{0:dd/M/yyyy}" and time DisplayFormat as "{0:hh:mm tt}"

[DataType(DataType.DateTime)]
[Display(Name = "Date")]
[DisplayFormat(DataFormatString = "{0:dd/M/yyyy}", ApplyFormatInEditMode = true)]
public DateTime LogInDate { get; set; }

[DataType(DataType.DateTime)]
[Display(Name = "Time In")]
[DisplayFormat(DataFormatString = "{0:hh:mm tt}", ApplyFormatInEditMode = true)]
public DateTime LogInTime { get; set; }

View Code:

    <div class="form-group">
        @Html.LabelFor(model => model.LogInDate, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.LogInDate, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.LogInDate, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.LogInTime, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.LogInTime, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.LogInTime, "", new { @class = "text-danger" })
        </div>
    </div>

Here is the HTML for date:

<input class="form-control text-box single-line input-validation-error" data-val="true" data-val-date="The field Date must be a date." data-val-required="The Date field is required." id="LogInDate" name="LogInDate" type="datetime" value="">

And HTML for time:

<input class="form-control text-box single-line input-validation-error" data-val="true" data-val-date="The field Time In must be a date." data-val-required="The Time In field is required." id="LogInTime" name="LogInTime" type="datetime" value="">

When I want to enter data, I get this error: enter image description here

Index page works fine:

[Date/Time displays correctly]

Also If I can get this sorted, can I use any of the Format Specifier (From Microsoft's "Custom Date and Time Format Strings" Page) in DataFormatString to display/edit the date/time as I need?

Thank you very much for helping me.

Shiva
  • 20,575
  • 14
  • 82
  • 112
Tonmoy
  • 2,008
  • 2
  • 10
  • 16
  • 1
    `LogInTime` needs to be `TimeSpan`, not `DateTime`. And if you want client side validation for dates in `dd/MM/yyyy` format, then you need to reconfigure the `$.validator` –  May 23 '17 at 04:46
  • 1
    Please refer to this [Question](https://stackoverflow.com/questions/16872493/validating-time-only-input-in-asp-net-mvc-unobtrusive-validation) – mmushtaq May 23 '17 at 04:49

0 Answers0