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
Related
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:
I've been away from ASP.NET MVC for a while so forgotten some of the basics.
I have scoured SO for an answer, but none really seem to apply/work so this may seem like a duplicate question but it's really not, perhaps I just can't see the wood through the trees. I know I'm missing something obvious but cant remember what
I have a partial that I pass the model to that updates a property on the model (AddressDetails & ContactDetails).
Main page
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<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
#await Html.PartialAsync("../AddressDetails/Create.cshtml", Model)
#await Html.PartialAsync("../ContactDetails/Create.cshtml", Model)
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
And partial page
#model CareHome.Models.CareHomes
<div class="form-group">
<h4>AddressDetails</h4>
<hr />
</div>
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="AddressDetails.NumberStreetName" class="control-label"></label>
<input asp-for="AddressDetails.NumberStreetName" class="form-control" />
<span asp-validation-for="AddressDetails.NumberStreetName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="AddressDetails.Locality" class="control-label"></label>
<input asp-for="AddressDetails.Locality" class="form-control" />
<span asp-validation-for="AddressDetails.Locality" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="AddressDetails.Town" class="control-label"></label>
<input asp-for="AddressDetails.Town" class="form-control" />
<span asp-validation-for="AddressDetails.Town" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="AddressDetails.PostCode" class="control-label"></label>
<input asp-for="AddressDetails.PostCode" class="form-control" />
<span asp-validation-for="AddressDetails.PostCode" class="text-danger"></span>
</div>
This is working fine when I post data back to the controller
However, I want to reuse the partial which means I want to replace
#model CareHome.Models.CareHomes
in the partial with the property class (see further below) that the model uses.
So when I change it to
main
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<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
#await Html.PartialAsync("../AddressDetails/Create.cshtml", Model.AddressDetails)
#await Html.PartialAsync("../ContactDetails/Create.cshtml", Model.ContactInfo)
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
note that im passing the property through to the partial now not the model
#model CareHome.Models.AddressDetails
<div class="form-group">
<h4>AddressDetails</h4>
<hr />
</div>
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="NumberStreetName" class="control-label"></label>
<input asp-for="NumberStreetName" class="form-control" />
<span asp-validation-for="NumberStreetName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Locality" class="control-label"></label>
<input asp-for="Locality" class="form-control" />
<span asp-validation-for="Locality" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Town" class="control-label"></label>
<input asp-for="Town" class="form-control" />
<span asp-validation-for="Town" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PostCode" class="control-label"></label>
<input asp-for="PostCode" class="form-control" />
<span asp-validation-for="PostCode" class="text-danger"></span>
</div>
iv now changed the partial to use
#model CareHome.Models.AddressDetails
but when I post this to the controller it comes back null
I tried a million variations on the binding
// POST: CareHomes/Create
// 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]
//Create([Bind("CareHomesId,Name,ContactName,ContactNumber")] CareHomes careHomes)
public async Task<IActionResult> Create([Bind( "CareHomes,AddressDetails,ContactDetails")] CareHomes careHomes)
{
if (ModelState.IsValid)
{
_context.Add(careHomes);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["AddressDetailsId"] = new SelectList(_context.AddressDetails, "AddressDetailsId", "NumberStreetName", careHomes.AddressDetailsId);
ViewData["ContactDetailsId"] = new SelectList(_context.ContactDetails, "ContactDetailsId", "ContactName", careHomes.ContactDetailsId);
return View(careHomes);
}
but when I evaluate the ModelState I can see it's always missing. As the propertys of the model bind ok when i pass the model though why do they then not bind when i pass the property though
my classes are like so
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CareHome.Models
{
public class CareHomes
{
[Required]
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CareHomesId { get; set; }
[Required]
[Column(TypeName = "VARCHAR(256)")]
[StringLength(256, MinimumLength = 3)]
public string Name { get; set; }
public int? AddressDetailsId { get; set; }
public AddressDetails AddressDetails { get; set; }
public int? ContactDetailsId { get; set; }
public ContactDetails ContactInfo { get; set; }
public ICollection<Staff>? StaffMembers { get; set; }
}
}
and one of the properties in question
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CareHome.Models
{
public class AddressDetails
{
[Required]
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int AddressDetailsId { get; set; }
[Required]
[Column(TypeName = "VARCHAR(256)")]
[StringLength(256, MinimumLength = 3)]
[Display(Name = "House No & Street Name")]
public string NumberStreetName { get; set; }
[Column(TypeName = "VARCHAR(256)")]
[StringLength(256, MinimumLength = 3)]
public string? Locality { get; set; }
[Required]
[Column(TypeName = "VARCHAR(256)")]
[StringLength(256, MinimumLength = 3)]
public string Town { get; set; }
[Required]
[Column(TypeName = "VARCHAR(16)")]
[StringLength(16, MinimumLength = 4)]
[RegularExpression(#"^(([A-Z]{1,2}\d[A-Z\d]?|ASCN|STHL|TDCU|BBND|[BFS]IQQ|PCRN|TKCA) ?\d[A-Z]{2}|BFPO ?\d{1,4}|(KY\d|MSR|VG|AI)[ -]?\d{4}|[A-Z]{2} ?\d{2}|GE ?CX|GIR ?0A{2}|SAN ?TA1)$", ErrorMessage = "Please enter a valid UK post code in upper case")]
public string PostCode { get; set; }
public CareHomes? CareHomes { get; set; }
}
}
I have tried adding bind animations like
[BindProperty]
to the property and adding hidden fields in the partual
#Html.HiddenFor(m => m.AddressDetailsId)
#Html.HiddenFor(m => m.AddressDetails)
As per some suggestions from some of the many SO searches I did, but no dice....so please...what am I missing?
I even tried #html.EditorFor but that seems to have the same problem
EDIT
Using #Jonesopolis suggestion I can see from the form being posted back when it uses the model:
?this.Request.Form.ToArray()
{System.Collections.Generic.KeyValuePair<string, Microsoft.Extensions.Primitives.StringValues>[11]}
...
[4]: {[AddressDetails.CareHomes, {}]}
[5]: {[AddressDetailsId, {}]}
[6]: {[AddressDetails.NumberStreetName, {sad}]}
[7]: {[AddressDetails.Locality, {sad}]}
[8]: {[AddressDetails.Town, {wales}]}
[9]: {[AddressDetails.PostCode, {CF83 8RD}]}
vs when i pass the property
?this.Request.Form.ToArray()
{System.Collections.Generic.KeyValuePair<string, Microsoft.Extensions.Primitives.StringValues>[11]}
...
[4]: {[CareHomes, {}]}
[5]: {[AddressDetailsId, {0}]}
[6]: {[NumberStreetName, {test street}]}
[7]: {[Locality, {}]}
[8]: {[Town, {wales}]}
[9]: {[PostCode, {CF83 8RD}]}
so clearly the "AddressDetails" is missing so MVC cant map the propery to the CareHomes class object on the binding because the property name is missing. So i know what the issue is not how to fix it though, How do I set the property name on the partual propertys so they map back to the parent object class. I though about a costom binder but not having much luck figuring that one out.
On a side note, intrestingly enough if in the partent model I do this :
#Html.EditorFor(m => m.AddressDetails.NumberStreetName)
then bind like so
public async Task<IActionResult> Create([Bind(include: "CareHomes,AddressDetails")] CareHomes careHomes)
I can at least get the EditorFor to pull though on the parent
Finally worked it out, seems model binding wasn't the issue, I just had to set the id and name properties on the form controls in the partial to match that of the object on the model action, e.g. id="AddressDetails_NumberStreetName" name="AddressDetails.NumberStreetName"
so adding
<div class="form-group">
<label asp-for="NumberStreetName" class="control-label"></label>
<input asp-for="NumberStreetName" id="AddressDetails_NumberStreetName" name="AddressDetails.NumberStreetName" class="form-control" />
<span asp-validation-for="NumberStreetName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Locality" class="control-label"></label>
<input asp-for="Locality" id="AddressDetails_Locality" name="AddressDetails.Locality" class="form-control" />
<span asp-validation-for="Locality" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Town" class="control-label"></label>
<input asp-for="Town" id="AddressDetails_Town" name="AddressDetails.Town" class="form-control" />
<span asp-validation-for="Town" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Postcode" class="control-label"></label>
<input asp-for="Postcode" id="AddressDetails_Postcode" name="AddressDetails.Postcode" class="form-control" />
<span asp-validation-for="Postcode" class="text-danger"></span>
</div>
allows it to properly map to the contoller model
public async Task<IActionResult> Create([Bind(include: "CareHomes, Name,AddressDetails, ContactInfo")] CareHomes careHomes)
I worked it out when I put the partial mark up in the main form and looked at the HTML markup and compared it to when it was a partial. I hope this helps someone else someday
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:
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
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; }