@ Html.DisplayFor-DateFormat ( "mm / dd / yyyy")
mm/dd/yyyy
날짜 형식을 원하는 다음 면도기 코드가 있습니다.
Audit Date: @Html.DisplayFor(Model => Model.AuditDate)
나는 여러 가지 접근 방식을 시도했지만 그 접근 방식 중 어느 것도 내 상황에서 작동하지 않습니다.
내 AuditDate는 DateTime?
유형입니다.
나는 이와 같은 것을 시도 하고이 오류가 발생했습니다.
@Html.DisplayFor(Model => Model.AuditDate.Value.ToShortDateString())
추가 정보 : 템플릿은 필드 액세스, 속성 액세스, 단일 차원 배열 인덱스 또는 단일 매개 변수 사용자 지정 인덱서 식에만 사용할 수 있습니다.
이것을 시도 :
@Html.DisplayFor(Model => Model.AuditDate.ToString("mm/dd/yyyy"))
'ToString'메서드에 대한 오버로드는 1 개의 인수를 사용
를 사용하는 경우 속성을 DisplayFor
통해 형식을 정의 DisplayFormat
하거나 사용자 정의 표시 템플릿을 사용해야합니다. (사전 설정의 전체 목록은 여기DisplayFormatString
에서 찾을 수 있습니다 .)
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime? AuditDate { get; set; }
또는보기를 만듭니다 Views\Shared\DisplayTemplates\DateTime.cshtml
.
@model DateTime?
@if (Model.HasValue)
{
@Model.Value.ToString("MM/dd/yyyy")
}
DateTime
하지만 시간을 인코딩하는 경우에도 모든에 적용됩니다 . 날짜 전용 속성에만 적용 Views\Shared\DisplayTemplates\Date.cshtml
하려면 DataType
속성에서 및 속성을 사용하십시오.
[DataType(DataType.Date)]
public DateTime? AuditDate { get; set; }
마지막 옵션은 DisplayFor
속성을 사용하지 않고 대신 직접 렌더링하는 것입니다.
@if (Model.AuditDate.HasValue)
{
@Model.AuditDate.Value.ToString("MM/dd/yyyy")
}
해당 모델 속성의 값을 단순히 출력하는 경우 DisplayFor
html 도우미 가 필요하지 않고 적절한 문자열 형식으로 직접 호출하면됩니다 .
Audit Date: @Model.AuditDate.Value.ToString("d")
출력해야 함
Audit Date: 1/21/2015
마지막으로 감사 날짜가 null 일 수 있으므로 nullable 값의 형식을 지정하기 전에 조건부 확인을 수행해야합니다.
@if (item.AuditDate!= null) { @Model.AuditDate.Value.ToString("d")}
수신되는 오류를 인터넷 검색하면 이 답변이 제공 되며 , 이는 오류가 Html 도우미에서 Model이라는 단어를 사용하여 발생했음을 보여줍니다. 예를 들어 @Html.DisplayFor(Model=>Model.someProperty)
. Model
예를 들어 이외의 다른 것을 사용하도록 변경 @Html.DisplayFor(x=>x.someProperty)
하거나 이러한 도우미에서 대문자 M
를 소문자 m
로 변경하십시오 .
디스플레이 템플릿 사용에 대한 @ChrisPratt의 답변이 잘못되었습니다. 작동하는 올바른 코드는 다음과 같습니다.
@model DateTime?
@if (Model.HasValue)
{
@Convert.ToDateTime(Model).ToString("MM/dd/yyyy")
}
그것은 .ToString()
for Nullable<DateTime>
가 Format
parameter를 받아들이지 않기 때문 입니다 .
비슷한 방식으로 구현했습니다.
- TextBoxFor 를 사용 하여 날짜를 필수 형식으로 표시하고 필드를 읽기 전용으로 만듭니다.
@Html.TextBoxFor(Model => Model.AuditDate, "{0:dd-MMM-yyyy}", new{@class="my-style", @readonly=true})
2. CSS로 TextBox에 윤곽선 과 테두리 를 0으로 지정 합니다.
.my-style {
outline: none;
border: none;
}
그리고 ...... 끝났습니다 :)
나를 위해 사용하기에 충분했습니다.
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime StartDate { set; get; }
파헤 치고 나서 컨트롤러의 액션 메서드에 CultureInfo ( "en-US") 를 갖도록 Thread
의 CurrentCulture 값을 설정했습니다 .
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
모든보기에서이 설정을 사용하려는 경우 몇 가지 다른 옵션 이 있습니다.
CurrentCulture
속성 값 정보 :
하는 CultureInfo 함께 관련 객체와이 속성에 의해 반환되는 객체는, 날짜, 시간, 숫자, 통화 값, 텍스트의 정렬 순서, 케이싱 규칙 및 문자열 비교에 대한 기본 형식을 결정합니다.
출처 : MSDN CurrentCulture
참고 :CurrentCulture
컨트롤러가 이미 CultureInfo("en-US")
날짜 형식이 인 또는 이와 유사한 상태로 실행중인 경우 이전 속성 설정은 선택 사항 일 수 "MM/dd/yyyy"
있습니다.
CurrentCulture
속성을 설정 한 후 코드 블록을 추가하여 날짜를 "M/d/yyyy"
뷰의 형식으로 변환합니다 .
@{ //code block
var shortDateLocalFormat = "";
if (Model.AuditDate.HasValue) {
shortDateLocalFormat = ((DateTime)Model.AuditDate).ToString("M/d/yyyy");
//alternative way below
//shortDateLocalFormat = ((DateTime)Model.AuditDate).ToString("d");
}
}
@shortDateLocalFormat
위의 @shortDateLocalFormat
변수는 ToString("M/d/yyyy")
작품 으로 형식이 지정됩니다 . ToString("MM/dd/yyyy")
를 사용 하면 처음에 한 것처럼 문제가 발생하지 않습니다 . Tommy ToString("d")
가 추천하는 작품도 마찬가지입니다. 실제로 "d"
는 "짧은 날짜 패턴"을 나타내며 다른 문화 / 언어 형식으로도 사용할 수 있습니다.
위의 코드 블록은 멋진 도우미 메서드 또는 이와 유사한 방법 으로 대체 될 수도 있습니다 .
예를 들면
@helper DateFormatter(object date)
{
var shortDateLocalFormat = "";
if (date != null) {
shortDateLocalFormat = ((DateTime)date).ToString("M/d/yyyy");
}
@shortDateLocalFormat
}
can be used with this helper call
@DateFormatter(Model.AuditDate)
Update, I found out that there’s alternative way of doing the same thing when DateTime.ToString(String, IFormatProvider) method is used. When this method is used then there’s no need to use Thread
’s CurrentCulture
property. The CultureInfo("en-US")
is passed as second argument --> IFormatProvider to DateTime.ToString(String, IFormatProvider)
method.
Modified helper method:
@helper DateFormatter(object date)
{
var shortDateLocalFormat = "";
if (date != null) {
shortDateLocalFormat = ((DateTime)date).ToString("d", new System.Globalization.CultureInfo("en-US"));
}
@shortDateLocalFormat
}
I have been using this change in my code :
old code :
<td>
@Html.DisplayFor(modelItem => item.dataakt)
</td>
new :
<td>
@Convert.ToDateTime(item.dataakt).ToString("dd/MM/yyyy")
</td>
You can use the [DisplayFormat] attribute on your view model as you want to apply this format for the whole project.
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public Nullable<System.DateTime> Date { get; set; }
Maybe try simply
@(Model.AuditDate.HasValue ? Model.AuditDate.ToString("mm/dd/yyyy") : String.Empty)
also you can use many type of string format like .ToString("dd MMM, yyyy") .ToString("d") etc
I had a similar issue on my controller and here is what worked for me:
model.DateSigned.HasValue ? model.DateSigned.Value.ToString("MM/dd/yyyy") : ""
"DateSigned" is the value from my model The line reads, if the model value has a value then format the value, otherwise show nothing.
Hope that helps
This is the best way to get a simple date string :
@DateTime.Parse(Html.DisplayFor(Model => Model.AuditDate).ToString()).ToShortDateString()
In View Replace this:
@Html.DisplayFor(Model => Model.AuditDate.Value.ToShortDateString())
With:
@if(@Model.AuditDate.Value != null){@Model.AuditDate.Value.ToString("dd/MM/yyyy")}
else {@Html.DisplayFor(Model => Model.AuditDate)}
Explanation: If the AuditDate value is not null then it will format the date to dd/MM/yyyy, otherwise leave it as it is because it has no value.
You could use Convert
<td>@Convert.ToString(string.Format("{0:dd/MM/yyyy}", o.frm_dt))</td>
See this answer about the No overload for method 'ToString' takes 1 arguments
error.
You cannot format a nullable DateTime - you have to use the DateTime.Value property.
@Model.AuditDate.HasValue ? Model.AuditDate.Value.ToString("mm/dd/yyyy") : string.Empty
Tip: It is always helpful to work this stuff out in a standard class with intellisense before putting it into a view. In this case, you would get a compile error which would be easy to spot in a class.
참고URL : https://stackoverflow.com/questions/28114874/html-displayfor-dateformat-mm-dd-yyyy
'Nice programing' 카테고리의 다른 글
ScrollViewer가 StackPanel 내에서 작동하도록하려면 어떻게해야합니까? (0) | 2020.11.01 |
---|---|
실용적인 HTTP 헤더 길이 제한이 있습니까? (0) | 2020.11.01 |
Android Studio 드로어 블 폴더 (0) | 2020.10.31 |
Java 중요 섹션에서 무엇을 동기화해야합니까? (0) | 2020.10.31 |
@로 매개 변수 이름 접두사 C # (0) | 2020.10.31 |