get MM/dd/yyyy only in razor for datetime

2019-06-26 07:15发布

问题:

I have something code like this

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

and working fine. But It is retrieving the whole data from my sql

Output from current code

3/22/2017 12:00:00 AM

Desired output

3/22/2017

I try to use a code like this @Html.ValidationMessageFor(model => model.VoluntaryWork.DateEnded.Value.ToShortDateString()) but it gives me an error

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions

I try to search on google and found this but for me its a long method? And I am new in that method so I don't know how to use it.

Is there any shortest way to achieve the desired output?.

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>
 }

回答1:

You can apply a DisplayFormatAttribute to your property

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

and the format will be respected by the EditorFor() method.

Alternatively you can use

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


回答2:

The simpliest way is:

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

Fortunatly EditorFor hepler doesn't have this overload. that's why you should use TextBoxFor html helper

Update:

MVC 3 doesn't have this overload. So the simpliest way to solve your problem will be use not strongly typed helper like this:

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


回答3:

Annotate your property in the model like this:

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

It will hide the time from your dateEnded property.



回答4:

Try this code

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


回答5:

To add a property to your model add this code:

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

Then in your PartialView:

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