---
# System prepended metadata

title: .NET MVC 日期選擇器衍生
tags: [MVC, .NET]

---

# .NET MVC 日期選擇器衍生
----
###### tags: `.NET` `MVC`

前端code

```csharp=
<div class="form-group input-group-sm">
    @Html.LabelFor(m => m.TestDate)
    @Html.TextBoxFor(m => m.TestDate, new { @class = "form-control datepicker", placeholder = "Enter Drop-off date here..." })
    @Html.ValidationMessageFor(m => m.TestDate)
</div>
```

```javascript=
@section Scripts{
    // 引入jQ
    $('.datepicker').datetimepicker({
        format: 'YYYY/MM/DD HH:mm',
    });
}
```
後端接值

ViewModel
分成兩種
```csharp=
[Display(Name = "日期")]
[Required]
[DataType(DataType.DateTime)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:YYYY/MM/DD HH:mm}")]
public DateTime TestDate { get; set; }
```

多出`?`的

```csharp=
[Display(Name = "日期")]
[Required]
[DataType(DataType.DateTime)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:YYYY/MM/DD HH:mm}")]
public DateTime? TestDate { get; set; }
```
Controller寫的方式不同
```csharp=
// 不能加?
DateTime time = model.TestDate;

// 加上?後
DateTime time = model.TestDate.GetValueOrDefault();
var time2 = model.TestDate.GetValueOrDefault();

return Content(time.ToString());
```


