MVC5 with scaffolding; remove time from a datetime field - datetime

I am creating an MVC5 project which utilizes scaffolding and has an EDM as a model. I want to use server-side code to remove the time portion of my datetime fields rather than parsing it with JQuery.
How do I achieve this?

Try [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
And if you dont want to validate it use a questionmark after the DateTime property like so public DateTime? Date{ get; set; }
[DisplayName("Date of Birth:")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
[Display(Order = 35)]
public DateTime? CODoB { get; set; }
or you can just use editfor and display for templates here is a link

You can add EditorTemplate in the view folder, you need to create EditorTemplates folder and then create DateTime.cshtml and there you can pass the DateTime that came from Model to the default editor only the date portion like:#Html.EditorFor(x=>x.Date)
If that is not useful for you you need to tell me, where do you need to trim the time portion only in the view or also in database, and if so is your model code first or DataBase first approach

Related

.NET core backend, model with Required nullable being created from Postman without required data sent in

I have a model with the following property:
[Required]
public DateTime? CreatedDate { get; set; }
This is Required and nullable, which is excactly what I want, trying to avoid empty or default date set, forcing user/frontend to send a date.
My Dto has no annotations and the property is not nullable:
public DateTime CreatedDate { get; set; }
Controller:
public async Task<IActionResult> Create([FromBody] InputDto input)
{
var creatInputId = await inputService.AddAsync(input);
return Ok(creatInputId );
}
Service maps Dto to model using Automapper:
var input = _mapper.Map<InputModel>(inputDto);
When I test this controller from Postman, database is updated whether I supply a CreatedDate or not, from frontend it does not. When using Postman, CreatedDate in database is set to 01-01-0001.
Should I use dataannotations in my Dto as well? I want to avoid default date/prohibit saving input unless a non-default date is given.
The Dto gets hit before the model. As it is not required or nullable it is filled with default value which is quite similar to 01-01-0001 in case of DateTime.
You need to put your annotations in the Dto also.

Cannot drop database. Because it is in currently use. EF Code first approach

I am using code first entity framework approach. I have changed the name Plane_EcoClass to Plane_Class property to the table in the database. It is showing with old property name in the db .How can I update the new property name?. Please let me know how to resolve this error.
public class Plane
{
[Key]
public int Plane_id { get; set; }
public string Plane_Name { get; set; }
public string Plane_No { get; set; }
public string Plane_Class { get; set; }
public virtual List<User>Users { get; set; }
}
you need to add a migration and update the database for the change to affect the database. In the package manager console, type something like:
add-migration YourMigrationName
to create the migration. Review the migration code. Be aware that Entity Framework may try to drop the previously named column and add a column for the new name. This can potentially cause data loss. If this is the case and not desired, then you can manually change the code to use the RenameColumn method.
After adding the migration, you can apply it to the database by going back to the package manager console and typing:
update-database
and then hitting enter. At this point, the package manager console will give you some output regarding running migrations and your seed method and then the database should reflect the updated column name

How to set DataAnnotations for Date in Database First EF 6 on MVC5

There is a method to set format in Code First Migration
i.e:
..
[DisplayFormat(ApplyFormatInEditMode=true, DataFormatString = "{0:d}")]
public Nullable<System.DateTime> DeliveredDate { get; set; }
..
However, I could achieve same logic in Database First Migration, since every change is the database is updating the models.
So, my question is: How to set DataAnnotations like (DisplayFormat, DataFormatString so on.) in Database first migration? Is is possible? If possible, how to implement it.
You can utilize the fact that the generated entity classes are partial and associate metadata though another class and MetadataTypeAttribute.
E.g., in some code file not affected by the code generation, you would write something like this:
[MetadataType(typeof(YourEntityMetadata))]
partial class YourEntity { }
class YourEntityMetadata
{
[DisplayFormat(ApplyFormatInEditMode=true, DataFormatString = "{0:d}")]
public Nullable<System.DateTime> DeliveredDate { get; set; }
}
The "metadata" class does not need to include all properties of the entity - just the ones you want to associate data annotations with.
Reference: EF Database First with ASP.NET MVC: Enhancing Data Validation
You could change view model property with the [DisplayFormat] attribute:
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",
ApplyFormatInEditMode = true)]
public DateTime DeliveredDate { get; set; }
and in your view:
#Html.EditorFor(x => x.DeliveredDate )
or, for displaying the value,
#Html.DisplayFor(x => x.DeliveredDate )
or you can do like this:
#Html.TextBox("MyDate", Model.DeliveredDate .ToLongDateString())

Asp.Net MVC Validations Not working

[Display(Name = "SentDoc_lblDescription ", ResourceType = typeof(EXTDocuments.Resources))]
[Required(ErrorMessage="Description Required")]
public string Description {get;set;}
This Description Property is required in business logic.
When I am clicking submit button it throws an error.
The error is decription is null, I want to validate that property from within the UI.
I want to recall running into something like this and currently use this attribute set in order to ensure my strings get validated correctly:
[Required]
[MaxLength(200)]
[MinLength(5)]
[Display(Name = "Name")]
public string ItemName { get; set; }
By using the MinLength and Required, you get a required string with a minimum length. Hopefully this helps you out.

Entity Framework DateTime format when editing entry

I have a Timetable model which only has two attributes at the moment, an Id and Date. It's defined as so:
public class Timetable
{
public int Id { get; set; }
[Required, Column(TypeName = "Date"), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime Date { get; set; }
}
I then scaffolded some basic CRUD functionality, and thanks to the DisplayFormat annotation it's allowing me to create timetables with dates in the dd/MM/yyyy format. However, when I edit an existing timetable, the application is populating the Date text box with 01/01/2015 00:00:00 (see screenshot).
Is there any way to make my application only use the date, rather than date and time?
In order to render the browsers datepicker (<input type="date" ..>) using EditorFor() you need the following attributes on the property (note the ISO format means the date will be displayed in accordance with the browser culture)
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode=true)]
[DataType(DataType.Date)]
public DateTime Date { get; set; }
and in the view
#Html.EditorFor(m => m.Date)
Note the HTML5 date input is not supported in older browsers, and not at all in FireFox - see comparison here

Resources