Format date within View in ASP.NET Core MVC

前端 未结 9 2136
借酒劲吻你
借酒劲吻你 2020-12-30 09:51

I have problem in regarding with converting the datetime to date using a model.

Model from Class Library

public partial class LoanCo         


        
相关标签:
9条回答
  • 2020-12-30 10:23

    Add [DataType(DataType.Date)] in your model

    [Column(TypeName = "Date")]
    [DisplayName("Date of birth")]
    [DataType(DataType.Date)] 
    
    0 讨论(0)
  • 2020-12-30 10:24

    Simple and practical, use asp-format, example:

    <input asp-for="MyDate" asp-format="{0:dd/MM/yyyy}" class="form-control" />
    

    Or:

    @Html.TextBoxFor(model => model.MyDate, "{0:dd/MM/yyyy}", new { @class = "form-control" })
    
    0 讨论(0)
  • 2020-12-30 10:26

    This might be the wrong solution to the problem being asked, but I hope it helps someone. If you are trying to input only a date (without time) Model.IsValid will throw back a validation error saying the date input format is incorrect. To solve this problem, simply Add this to your model.

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

    Using data attributes inside asp.net have the benefit of automatically being supported by jQuery client-side validation. (Generated by Asp.Net)

    0 讨论(0)
  • 2020-12-30 10:26

    I have also solved this problem using .ToString("d"). I received output of "MM/DD/YYYY".

    0 讨论(0)
  • 2020-12-30 10:29

    For those who get here wanting to change date format of a model in the view regardless of Model class (Its what I expected to be answering). This works in both Razorpages and MVC.

    Just add .ToString("dd/MM/YYYY") to the property you're displaying.

    e.g.

    @Model.DateOfBirth.ToString("<Use formatting here>")
    

    This is great if you only want to show part of a date say month and year, but elsewhere you need to show the day and the time.

    0 讨论(0)
  • 2020-12-30 10:32

    Try it with this in your model:

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
    

    And In your controller change DateTime to Date :

    myList.loanContract = new LoanContract { LoanDateStart = Date.Today };
    

    Hope this help you.

    0 讨论(0)
提交回复
热议问题