Get MM / dd / yyyy only in razor for datetime

I have something like this

 @Html.EditorFor(model => model.VoluntaryWork.DateEnded)
 @Html.ValidationMessageFor(model => model.VoluntaryWork.DateEnded)

and it works fine. But it retrieves all the data from my sql

Exit Current Code

3/22/2017 12:00:00 AM

Desired Conclusion

3/22/2017

I am trying to use such code @Html.ValidationMessageFor(model => model.VoluntaryWork.DateEnded.Value.ToShortDateString()), but it gives me an error

Templates can only be used with access to a field, access to properties, an index of a one-dimensional array, or one-parameter expressions of a custom indexer

I am trying to do a google search and found this , but is this a long method for me? And I'm new to this method, so I don’t know how to use it.

Is there any shortest way to achieve the desired result?

Update

Controller code

PersonVoluntaryWork pvw = db.PersonVoluntaryWorks.Single(vw => vw.VoluntaryWorksId == id);
return PartialView("_NewPersonVoluntaryWorks", pvw);

View

@model System.Models.PersonVoluntaryWork
@using (Html.BeginForm())
{
  <td>
          @Html.EditorFor(model => model.VoluntaryWork.DateEnded)
          @Html.ValidationMessageFor(model => model.VoluntaryWork.DateEnded)       
</td>
 }
+4
5

DisplayFormatAttribute

[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime DateEnded { get; set; }

EditorFor().

@Html.TextBoxFor(m => m.VoluntaryWork.DateEnded, "{0:d}", null)
+4

:

@Html.TextBoxFor(model => model.VoluntaryWork.DateEnded, "{0:dd/MM/yyyy}")

Fortunatly EditorFor hepler . TextBoxFor html helper

Update:

MVC 3 . , , :

@Html.TextBox("VoluntaryWork_DateEnded", 
    Model.VoluntaryWork.DateEnded.HasValue
    ? Model.VoluntaryWork.DateEnded.Value.ToString("dd/MM/yyyy")
    : DateTime.Now.ToString("dd/MM/yyyy"))
+2

:

[DataType (DataType.Date)]
public DateTime? DateEnded {get; ; }

dateEnded.

0

@Html.EditorFor(model => model.VoluntaryWork.DateEnded, 
    new { @Value = model.VoluntaryWork.DateEnded.ToString("MM/dd/yyyy") })
-1

, :

public string ReturnDateForDisplay  
{  
    get  
    {  
       return this.VoluntaryWork.DateEnded.ToString("d");  
    }  
}

Then in your PartialView:

@Html.EditorFor(model => model.ReturnDateForDisplay)

-1
source

Source: https://habr.com/ru/post/1672893/


All Articles