Problem with inputfield DateTime and TimeSpan - c#

I'm having trouble with some ASP/C# inputfields. Here is a screencapture of what I have:
It is a inputfield for movies in a cinema. StartAt is the startdate of a timetable, EndAt is the enddate of the timetable and the Time represents the daily time within the two dates that the movie is playing daily.
Problem is I'm European and normal pattern would be dd-mm-yyyy for us. I cannot get that done. The bigger problem is the Timespan. That should be HH:mm (24h clock) and not HH:mm:ss.
Here is my View-code:
<div class="form-group">
<label asp-for="StartAt" class="control-label"></label>
<input asp-for="StartAt" class="form-control" />
<span asp-validation-for="StartAt" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="EndAt" class="control-label"></label>
<input asp-for="EndAt" class="form-control" />
<span asp-validation-for="EndAt" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Time" class="control-label"></label>
<input asp-for="Time" class="form-control" />
<span asp-validation-for="Time" class="text-danger"></span>
</div>
And here is my model:
public class MovieRuntime
{
public int Id { get; set; }
public int MovieId { get; set; }
public int HallId { get; set; }
[DataType(DataType.Date)]
[Column(TypeName = "Date")]
public DateTime StartAt { get; set; }
DataType(DataType.Date)]
[Column(TypeName = "Date")]
public DateTime EndAt { get; set; }
[DataType(DataType.Time)]
[Column(TypeName = "Time")]
public TimeSpan Time { get; set; }
[ForeignKey("MovieId")]
public virtual Movie Movie { get; set; } = null!;
[ForeignKey("HallId")]
public virtual Hall Hall { get; set; } = null!;
}
I tried to use DisplayFormat in the model, but this didn't help:
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
What do I miss here?

You can use asp-formatting to specify the format of the date and time.
asp-format="{0:dd.MM.yyyy}"
<div class="form-group">
<label asp-for="StartAt" class="control-label"></label>
<input asp-for="StartAt" asp-format="{0:dd.MM.yyyy}" type="date" class="form-control" />
<span asp-validation-for="StartAt" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="EndAt" class="control-label"></label>
<input asp-for="EndAt" asp-format="{0:dd.MM.yyyy}" type="date" class="form-control" />
<span asp-validation-for="EndAt" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Time" class="control-label"></label>
<input asp-for="Time" asp-format="{0:HH:mm}" type="time" class="form-control" />
<span asp-validation-for="Time" class="text-danger"></span>
</div>

Html date input isn't offically possible to format change. Pure element always show based on browser culture.
You should use 3rd library (like bootstrap datepicker, jquery datepicker) or you can hack with css, js (ex : https://stackoverflow.com/a/31162426/14671235)

I made a workaround for the biggest problem, the TimeSpan. I changed the input-field to a textbox:
<input type="text" class="form-control" placeholder="i.e 12:00" name="time" onchange="validateHhMm(this)" required=""/>
I added a javascript regex-checker which changes the bg-color of the textfield red and disables the button when it's not the right expression:
<script>
function validateHhMm(inputField)
{
var isValid = /^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$/.test(inputField.value);
if (isValid) {
inputField.style.backgroundColor = '#bfa';
document.getElementById('addButton').disabled = false;
} else {
inputField.style.backgroundColor = '#fba';
document.getElementById('addButton').disabled = true;
}
return isValid;
}
</script>
Output is now like this:
For the Pattern problem, the problem was that my browser was on US-settings. That is why I got the US pattern. I changed it to Dutch and this was the output:

Related

Datetime from API , Create/post to API

I got two different projects, one API and one for the web(front).
I Can create a course through my API but when i try to post from my front-end i got this error,
FormatException: Input string was not in a correct format.
And it complains on this one,
<span asp-validation-for="CourseTitle" class="text-danger"></span>
</div>
<div class="col-2">
<label asp-for="CourseStart" class="control-label pt-2" style="font-size:20px;"></label>
</div>
<div class="col-10 pb-3">
<input asp-for="CourseStart" class="form-control" />
<span asp-validation-for="CourseStart" class="text-danger"></span>
</div>
<div class="col-2">
<label asp-for="CourseEnd" class="control-label pt-2" style="font-size:20px;"></label>
</div>
<div class="col-10 pb-3">
Somehow my CourseStart doesnt work, and my class looks like this,
[Key]
public int CourseId { get; set; }
[Required]
public string CourseTitle { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime CourseStart { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime CourseEnd { get; set; }
The problem i think i got is that when i save a course through the API i got Date like this,
"courseStart": "2022-12-15T00:00:00"
So i think its expecting T00:00:00 somehow? What do u think? I cant find anything on google....
I made it work, what i did was,
changed my class to this,
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime CourseStart { get; set; }
after that, inside my html file, i put in this,
<div class="col-2">
<label asp-for="CourseStart" class="control-label pt-2" style="font-size:20px;"></label>
</div>
<div class="col-10 pb-3">
<input asp-for="CourseStart" type="date" class="form-control" />
<span asp-validation-for="CourseStart" class="text-danger"></span>
</div>
problem was that, through html helper, it saved it in this format, yyyy-MM-dd, so i had to change it. U can probably customize it but its to complicated for me :)

ASP.NET Core MVC : retrieve DateTime from database into view

I'm quite new to ASP.NET Core MVC and I'm having trouble retrieving a DateTime value from the database into the 'Edit' razor view.
I can use the scaffolded views to create a new Activity Item and this displays correctly in the 'Index' list, and in the 'Details' view, but when I attempt to 'Edit' the entry the DateTime value doesn't pull through from the database.
I've done plenty of reading but the main thing I seem to get in search results is information about JQuery Datepickers.
Any advice on where to look, how to resolve would be very much appreciated.
Here is my model:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace MISDataRepo.Models
{
[Table("Activity",Schema = "coir")]
public partial class ActivityItem
{
public ActivityItem()
{
ActivityIdentifier = new HashSet<ActivityIdentifier>();
}
[Key]
public int ActivityItemId { get; set; }
[Required(ErrorMessage = "A valid Activity Name is required.")]
[Display(Name = "Activity Name")]
[StringLength(100)]
public string ActivityName { get; set; }
[Required]
[Display(Name = "Activity Type")]
public int ActivityTypeId { get; set; }
[Required]
[Display(Name = "Date Activity Created")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DateCreated { get; set; }
[Display(Name = "Date Activity Modified")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? DatetModified { get; set; }
[Required]
[Display(Name = "Created By (Employee ID)")]
[RegularExpression("^[1-9][0-9]{6}$", ErrorMessage = "A valid Employee ID is required!")]
public int? CreatedBy { get; set; }
[Display(Name = "Project Co-Ordinator (Employee ID)")]
[RegularExpression("^[1-9][0-9]{6}$", ErrorMessage = "A valid Employee ID is required!")]
public int? PC { get; set; }
[DefaultValue(true)]
public bool Live { get; set; }
public virtual ActivityType ActivityType { get; set; }
public virtual ICollection<ActivityIdentifier> ActivityIdentifier { get; set; }
}
}
Here is the view:
#model MISDataRepo.Models.ActivityItem
#{
ViewData["Title"] = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Edit</h1>
<h4>ActivityItem</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="ActivityItemId" />
<div class="form-group">
<label asp-for="ActivityName" class="control-label"></label>
<input asp-for="ActivityName" class="form-control" />
<span asp-validation-for="ActivityName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ActivityTypeId" class="control-label"></label>
<select asp-for="ActivityTypeId" class="form-control" asp-items="ViewBag.ActivityTypeId"></select>
<span asp-validation-for="ActivityTypeId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DateCreated" class="control-label"></label>
<input asp-for="#Html.DisplayFor(a => a.DateCreated)" class="form-control" />
<span asp-validation-for="DateCreated" class="text-danger"></span>
#*<input type="hidden" asp-for="DateCreated" type="date" placeholder="Enter Date Created" value="#Model.DateCreated" />*#
</div>
<div class="form-group">
<label asp-for="DatetModified" class="control-label"></label>
<input asp-for="#Html.DisplayFor(a => a.DatetModified)" class="form-control" />
<span asp-validation-for="DatetModified" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="CreatedBy" class="control-label"></label>
<input asp-for="CreatedBy" class="form-control" />
<span asp-validation-for="CreatedBy" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PC" class="control-label"></label>
<input asp-for="PC" class="form-control" />
<span asp-validation-for="PC" class="text-danger"></span>
</div>
<div class="form-group form-check">
<label class="form-check-label">
<input class="form-check-input" asp-for="Live" /> #Html.DisplayNameFor(model => model.Live)
</label>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Here are the 'Edit' methods of the controller
// GET: ActivityItems/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var activityItem = await _context.ActivityItem.FindAsync(id);
if (activityItem == null)
{
return NotFound();
}
ViewData["ActivityTypeId"] = new SelectList(_context.ActivityType, "ActivityTypeId", "ActivityTypeName", activityItem.ActivityTypeId);
return View(activityItem);
}
// POST: ActivityItems/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
//public async Task<IActionResult> Edit(int id, [Bind("ActivityItemId,ActivityName,ActivityTypeId,DateCreated,DatetModified,CreatedBy,PC,Live")] ActivityItem activityItem)
public async Task<IActionResult> Edit(int id, [Bind("ActivityItemId,ActivityName,ActivityTypeId,DatetModified,CreatedBy,PC,Live")] ActivityItem activityItem)
{
if (id != activityItem.ActivityItemId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(activityItem);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ActivityItemExists(activityItem.ActivityItemId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["ActivityTypeId"] = new SelectList(_context.ActivityType, "ActivityTypeId", "ActivityTypeName", activityItem.ActivityTypeId);
return View(activityItem);
}
But when I attempt to 'Edit' the entry the DateTime value doesn't pull
through from the database.
Yes, the issue you are having with the your View is pretty obvious due to your HTML Helper atrribute that is #Html.DisplayFor and the Property you have defined within your Model ActivityItem. You are probably getting following issue.
Problem:
How To Resolve:
Either you could use ViewModel or you can redefine your property public DateTime DateCreated { get; set; } by get rid of your annotations. However, I would prefer to use ViewModel. On the other hands, use the property like asp-for="DateCreated" within your edit view and get rid of your additional HTML helper class #Html.DisplayFor. Follow the below steps.
View Model:
public class ActivityItemViewModel
{
public int ActivityItemId { get; set; }
public string ActivityName { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DatetModified { get; set; }
}
Note: While loading your Edit view you certainly doesn't require annotations so you can ommit that.
View :
In view you are using additional HTML helper class #Html.DisplayFor which is not required in this scenario. You could try as following:
#model DotNet6MVCWebApp.Models.ActivityItemViewModel
#{
ViewData["Title"] = "Edit";
}
<h1>Edit</h1>
<h4>ActivityItem</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="ActivityItemId" />
<div class="form-group">
<label asp-for="ActivityName" class="control-label"></label>
<input asp-for="ActivityName" class="form-control" />
<span asp-validation-for="ActivityName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DateCreated" class="control-label"></label>
<input asp-for="DateCreated" class="form-control" />
<span asp-validation-for="DateCreated" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DatetModified" class="control-label"></label>
<input asp-for="DateCreated" class="form-control" />
<span asp-validation-for="DatetModified" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="ActivityList">Back to List</a>
</div>
Output:

Razor Pages - DateOnly and TimeOnly Bind to Html Input Controls?

how can u bind dateonly and timeonly fields to html controls such ass date picker and time picker? i am using Mariadb as rdbms , I want to show to the end user date and time picker inputs, so far the date and time picker wont work properly.
<form method="post">
<input hidden asp-for="Period.Periodid" />
<div class="border p-3 mt-4">
<div class="row mb-3">
<h4 class=" pl-3">Επεξεργασία Επαφής</h4>
</div>
<div asp-validation-summary="All" class="text-danger"></div>
<div class="mb-3">
<label asp-for="Period.StartDate">Ημερομηνία Έναρξης</label>
<input type="date" asp-for="Period.StartDate" class="form-control" />
<span asp-validation-for="Period.StartDate" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="Period.EndDate">Ημερομηνία Λήξης</label>
<input type="date" asp-for="Period.EndDate" class="form-control" />
<span asp-validation-for="Period.EndDate" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="Period.StartTime">Ώρα Έναρξης</label>
<input type="time" asp-for="Period.StartTime" class="form-control" />
<span asp-validation-for="Period.StartTime" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="Period.EndTime">Ώρα Λήξης</label>
<input type="time" asp-for="Period.EndTime" class="form-control" />
<span asp-validation-for="Period.EndTime" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary" style="width:150px;">Ενημέρωση</button>
<a asp-page="Index" class="btn btn-secondary" style="width:150px;">Λίστα</a>
</div>
model
public class Period
{
public int Periodid { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateOnly StartDate { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateOnly EndDate { get; set; }
[Required]
[DataType(DataType.Time)]
public TimeOnly StartTime { get; set; }
[Required]
[DataType(DataType.Time)]
public TimeOnly EndTime { get; set; }
}
dateonly and timeonly are not supported yet for form binding (they will support it in dotnet 7)
see related post and solutions
stackoverflow related issue

Datetime model cant be displayed on google chrome

I have datetime data type in my asp.net core mvc application it displays mm/dd/yyyy --:-- -- doest take input from datepicker . Readonly mode even displays this mm/dd/yyyy --:-- -- instead datetime passing to the model.what is solution there way to remove this data?
The default value format of datepicker is yyyy-mm-dd , if you set the displayFormat of DateTime type property , you should set the type="text" to the input , or you maybe get the error like The specified value "02/12/1995" does not conform to the required format, "yyyy-MM-dd". Here is a example:
Model:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int Age { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime Birth { get; set; }
}
View:
<div class="row">
<div class="col-md-4">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Id" />
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Email" class="control-label"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Age" class="control-label"></label>
<input asp-for="Age" class="form-control" />
<span asp-validation-for="Age" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Birth" class="control-label"></label>
<input type="text" asp-for="Birth" class="form-control" id="datepicker" />
<span asp-validation-for="Birth" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#datepicker").datepicker({
format: 'dd/mm/yyyy'
})
});
</script>
}
Result:
As my understanding from your question, you want to input date using datepicker and display the only date mm/dd/yyyy part instead of mm/dd/yyyy --:-- --.
You can achieve this by using data annotation with your model.
[DataType(DataType.Date)]
public DateTime Date { get; set; }
And in your razorview, you can Html helper to input and show date.
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control" } })
And for readonly show
#Html.DisplayFor(modelItem => item.Date)
Please check out this question for more understanding.
As Kanavos commented above, formats only apply when converting to text or parsing text.
If you wish for individual pieces of your DateTime object to be shown and others to be hidden, you can do something like:
var newFormat = dateTimeObj.ToString("<desired format>")
and replacing the "< desired format >" with one listed in the MS docs here: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tostring?view=netframework-4.8

Date and decimal validation ASP.NET Core

I have model for Persons
Here is class
public partial class Persons
{
public int Id { get; set; }
[Required(ErrorMessage = "Please write First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please write Last Name")]
public string LastName { get; set; }
[StringLength(11, MinimumLength = 3, ErrorMessage = "Personal Number is too long")]
[Remote(action: "PersonalNumberExists", controller: "Persons", ErrorMessage = "Personal Number is duplicated")]
public string PersonalNumber { get; set; }
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime? Birthdate { get; set; }
public string Gender { get; set; }
public decimal? Salary { get; set; }
}
Here is View
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div class="form-group">
<label asp-for="FirstName" class="control-label"></label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="LastName" class="control-label"></label>
<input asp-for="LastName" class="form-control" />
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PersonalNumber" class="control-label"></label>
<input asp-for="PersonalNumber" class="form-control" />
<span asp-validation-for="PersonalNumber" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Birthdate" class="control-label"></label>
<input asp-for="Birthdate" class="form-control" />
<span asp-validation-for="Birthdate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Gender" class="control-label"></label>
<input asp-for="Gender" class="form-control" />
<span asp-validation-for="Gender" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Salary" class="control-label"></label>
<input asp-for="Salary" class="form-control" />
<span asp-validation-for="Salary" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
</div>
I need to make date and decimal validation for Birthdate and Salary fields.
I mean just check is it date or no, for decimal (decimal validation and greater or equals 0)
I don't find any validation for it
How I can do this?
For validation, try like below
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
[Required]
public DateTime? Birthdate { get; set; }
public string Gender { get; set; }
[Required]
public decimal? Salary { get; set; }

Categories

Resources