get MM/dd/yyyy only in razor for datetime

2019-06-26 07:17发布

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

5条回答
萌系小妹纸
2楼-- · 2019-06-26 07:46

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楼-- · 2019-06-26 08:01

Try this code

@Html.EditorFor(model => model.VoluntaryWork.DateEnded, 
    new { @Value = model.VoluntaryWork.DateEnded.ToString("MM/dd/yyyy") })
查看更多
你好瞎i
4楼-- · 2019-06-26 08:04

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)
查看更多
Explosion°爆炸
5楼-- · 2019-06-26 08:11

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)

查看更多
再贱就再见
6楼-- · 2019-06-26 08:12

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.

查看更多
登录 后发表回答