当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - How to save a date into a database using @Html.DisplayFor

问题描述:

Hi guys I am new this place I have been recommended to this site. My problem is i have a application in MVC3 C# in asp.net2010 and this application adds, edits and deletes text from a database and my next step is to create a way in which allows a automated date to be inputted. Currently this is done manually when a user clicks on the link create new and inputs the details he/she has to input the date manually I would like a way in which when the user clicks on link create new the date is automatically there for them so they just press enter.

@Html.EditorFor(model => model.Posted) I have tried to edit this so it shows this:

<%: Html.TextBox("date", DateTime.Now.ToShortDateString()) %> /*This code does replace the @Html.EditorFor link above and does not save the date and just shows it a text box"*/.

@Html.DisplayFor(modelItem => item.MyDateTime.ToLongDateString())

@{var val = item.MyDateTime.ToLongDateString();

Html.DisplayFor(modelItem => val);

}

None of these methods work or properly can you please help me thank you

I have been at this for ages looked everywhere on Google and yahoo had no luck I know it has something to do with this @Html.EditorFor(model => model.Posted) as when i click on create new it allows the user to input a date manually.

Thank you for your time Please if you require more information on code Ect... just ask me

网友答案:

You could decorate your view model Posted property with the [DisplayFormat] attribute, like so:

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

Now, when in your view you use:

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

you will get the desired format. As far as only displaying the date without rendering an input field is concerned you could use the DisplayFor helper and it will still respect the desired format that you have defined on your view model:

@Html.DisplayFor(model => model.Posted)
分享给朋友:
您可能感兴趣的文章:
随机阅读: