Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

Change the date format in C# ASP .Net Core MVC

How should I make it readonly

@Html.TextBoxFor(m => m.Leave.FromDate, "{0:dd/MM/yyyy}", new { @class = "form-control  default-date-picker" })

Also is there any way to change the following from MM/dd/yyyy to dd/MM/yyyy

<input asp-for="@Model.Leave.TillDate" type="date" asp-format="{0:yyyy-MM-dd}" class="form-control datepicker" />

I have tried using

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

in the class but it does not work. Thanks!!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can see my test here,following is an example.

Class:

 public class Date
{   
    public Leave Leave { get; set; }
}
public class Leave
{
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? FromDate { get; set; }
   
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? TillDate { get; set; }
}

Action:

 public IActionResult Test()
    {
        var model = new Date
        {
            Leave=new Leave
            {
                FromDate=DateTime.Now,
                TillDate=DateTime.Now
            }
        };
        return View(model);
    }

View:

@model Date

@Html.TextBoxFor(m => m.Leave.FromDate, "{0:dd/MM/yyyy}", new { @class = "form-control  default-date-picker" })

<input type="text" asp-for="@Model.Leave.TillDate" class="form-control datepicker" />

@section Scripts{
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" />
     <script>
    $(document).ready(function () {
        $('#Leave_FromDate').datepicker({
            format: 'dd/mm/yyyy',
        }).attr('readonly', 'readonly');
        $('#Leave_TillDate').datepicker({
            format: 'dd/mm/yyyy',
        });
    });
</script>
}

And if you want the first one can't be change,you can set by:

 $('#Leave_FromDate').datepicker({
                format: 'dd/mm/yyyy',
            }).attr('disabled', 'true');

Test Result:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...