In MVC razor, I am putting current date in the database like this..
model.Returndate = DateTime.Now.Date.ToShortDateString();
Since the database field is a datetime datatype and I am converting the current date to string format, this is not working.. how can I do this? I am doing the string format because I want the date in mm/dd/yyyy format and not in mm/dd/yyyy hh:mm:ss time format..
EDIT:
In the controller I have
var model = new ViewModel();
model.ReturnDate = DateTime.Now;
return PartialView("PartialView", model);
In the partialview, I have
@Html.EditorFor(model => model.Returndate)
This is where its displaying the date as Date and Time together... I want just the date to be displayed. Not the time. I hope this edit explains better.
You could simply convert the datetime. Something like:
I had some problems with the other solutions on this page, so thought I'd drop this in.
So you only need to add "{0:d}" in the second parameter and you should be good to go.
I am not sure in Razor but in ASPX you do:
There must be something similar in Razor. Hopefully this will help someone.
If the column type is DateTime in SQL then it will store a time where you pass one or not.
It'd be better to save the date properly:
and then format it when you need to display it:
Or if you're using EditorFor:
or
To add a property to your model add this code:
Then in your PartialView:
EDIT:
Hi guys, just want to clarify for this answer that by my saying 'If you're using EditorFor', that means you need to have an EditorFor template for the type of value you're trying to represent.
Editor templates are a cool way of managing repetitive controls in MVC:
http://coding-in.net/asp-net-mvc-3-how-to-use-editortemplates/
You can use them for naive types like String as I've done above; but they're especially great for letting you template a set of input fields for a more complicated data type.
This works if you want to display in a TextBox:
If you have a for loop such as the one below.
Change @item.StartDate to @item.StartDate.Value.ToShortDateString()
This will remove the time just in case you can't annotate your property in the model like in my case.