I’m working on ASP.NET application, and I have an issue with date formatting.
TextBoxFor is displaying Date Format instead of date.
Regional Settings:
United Kingdom, date format: “yyyy-mm-dd”.
.NET Globalization - IIS Settings:
Culture: Invariant Language (Invariant Country)
Enable Client Based Culture: false
UI Culture: Invariant Language (Invariant Country)
File: Windows-1252
Requests: utf-8
Response Headers: utf-8
Responses: utf-8
MainView (I have tried ToShortDateString() and ToString("d")) :
<td>
#item.InvoiceDate.ToShortDateString()
</td>
<td>
#item.DueDate.ToString("d")
</td>
Edit View:
<div class="form-group">
<div class="col-md-10">
#Html.Label("Invoice Date:")
<div class="fiveSpace"></div>
#Html.TextBoxFor(model => model.InvoiceDate, "{0:d}", new { type = "date" })
#Html.ValidationMessageFor(model => model.InvoiceDate)
</div>
</div>
<div class="form-group">
<div class="col-md-10">
#Html.Label("Due Date:")
<div class="fiveSpace"></div>
#Html.TextBoxFor(model => model.DueDate, "{0:d}", new { type = "date" })
#Html.ValidationMessageFor(model => model.DueDate)
</div>
</div>
Model:
[Required(ErrorMessage = "Please select Invoice Date.")]
public DateTime? InvoiceDate { get; set; }
[Required(ErrorMessage = "Please select Due Date.")]
public DateTime? DueDate { get; set; }
And result:
Table row
Once I try to edit dates:
Date and Inspect element
Correct value is stored in "value" but TextBoxFor displays date format. Also, when I have changed regional setting to other country, in MainView I always received dates in format "dd/mm/yyyy" and in edit view dates were displayed with US format, "mm/dd/yyyy".
I have tried:
set up <globalization uiCulture="en-GB" culture="en-GB" /> in web.config
add [DisplayFormat(DataFormatString = "{0:d}"] to model
Is the problem on my side, or IIS?
Resolved.
I've replaced mentioned TextBoxFor with:
#Html.TextBoxFor(model => model.InvoiceDate, new { #type = "date", #Value = Model.InvoiceDate.Value.ToString("yyyy-MM-dd") })
and it works.
The TextBoxFor with type="date" converts it to the <input type="date"> HTML tag which doesn't support date format customization according to the MDN.
It can be achieved by some 3rd-party JS libraries like Masked Input Plugin for jQuery or datetime-input web component
Related
I am using following code to popup calendar for date in my razor view
Model
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
[DataType(DataType.Date)]
public Nullable<System.DateTime> EndTime { get; set; }
View
<div class="form-group">
#Html.LabelFor(model => model.EndTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.EndTime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EndTime, "", new { #class = "text-danger" })
</div>
</div>
Now I want to use DateTime instead of Date.What should be the DataFormat String?
My Try
Display(Name = "End Date Time")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}{1:HH/mm}")]
[DataType(DataType.DateTime)]
I am getting format exception?
Your EditorFor() method renders an input with type="date" because of the [DataType(DataType.Date)] attribute, which will generate the browsers HTML-5 datepicker (but this is only supported in Chrome and Edge).
To generate a HTML-5 datetimepicker, you need to render an input with type = "datetime-local" but there is no data annotation attribute for that. Instead you need to generate the type attribute yourself.
#Html.TextBoxFor(m => m.EndTime, "{0:s}", new { #type = "datetime-local", #class = "form-control" })
Note "{0:s}" is shortcut for "{0:yyyy-MM-ddTHH:mm:ss}" and will display the date and time in the browsers culture. Note also that you do not need your [DataType] attribute or the ApplyFormatInEditMode = true property in the [DisplayFormat] attribute since they apply only to EditorFor()
currently I have this datepicker which will hightlight today's date on the pop up calender but the editor for the date onLoad shows DD/MM/YYYY instead of aotopopulating it when the page loads. How do I solve this ?
This is how I display my datepicker in the html file:
<div class="form-group">
#Html.LabelFor(model => model.date, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.date)
#Html.ValidationMessageFor(model => model.date)
</div>
</div>
And this is how I define it:
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
Your EditorFor() method is rendering your browsers HTML-5 implementation of a datepicker, which requires that the format be yyyy-MM-dd (ISO format).
Change the attribute to
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")
public DateTime date { get; set; }
which will display the date in the browsers culture
Alternatively you can use
#Html.TextBoxFor(m => m.date, "{0:yyyy-MM-dd}", new { #type = "date" })
if you do not want to change the format that will be used in a DisplayFor() method.
Note also that type="date" is only supported in Chrome and Edge
I have the following
public decimal? Price {get;set;}
When I enter 3000.00 in to the textbox on the view (textbox below)
<div class="form-group">
<label class="col-lg-3 control-label no-padding-right">Price</label>
<div class="col-lg-5">
#Html.ValidationMessageFor(m => m.Price)
<div class="input-group">
<span class="input-group-addon">£</span>
#Html.TextBoxFor(m => m.Price, new { #class = "form-control", type = "text", id = "txtPrice", onkeypress = "return isNumberKey(event)" })
</div>
</div>
<label class="col-lg-4 control-label" style="text-align: left">Decimal format</label>
So it would look like this
It saves in the database as 3000.00 which is expected, but when I return back to the view to edit it the value in the textbox is 3000.0000
I have tried some of the solutions on here
Remove trailing zeros of decimal
I think the issue I have is the field on the view is of type decimal not a string, so I'm uncertain on how to format this decimal to remove the trailing zeros so it looks like picture above
You need to use the oveload of TextBoxFor that accepts a format string
#Html.TextBoxFor(m => m.Price, "{0:0.00}", new { #class = "form-control", type = "text", id = "txtPrice", onkeypress = "return isNumberKey(event)"})
Side notes:
Remove type="text". The html helper already adds this for you (add
is there a reason why you dont just use the default id rendered by
the helper, which would be id="Price"?).
Use Unobtrusive Javascript rather that polluting your markup
with behavior - e.g. $('#txtPrice').keypress(...
Can somebody tell me why "This field is required" and "Please insert database name" are being displayed instead of just "Please insert database name"?
This is my model :
public class InstallViewModel
{
[Required(AllowEmptyStrings = false, ErrorMessage = "Please insert database name")]
public string DatabaseName { get; set; }
and this is my view :
<div class="input-group">
<span class="input-group-addon">Database</span>
#Html.TextBoxFor(w => w.DatabaseName, new { #class = "form-control", placeholder = "Database name" })
</div>
#Html.ValidationMessageFor(w=> w.DatabaseName)
Thank you.
EDIT:
Can you see the image attached ? I have some problems uploading images.
The view is a partial view and this is the whole partial view:
#Html.ValidationMessageFor(w => w.DatabaseName)
<div class="input-group">
<span class="input-group-addon">Database</span>
#Html.TextBoxFor(w => w.DatabaseName, new { #class = "form-control", placeholder = "Database name" })
</div>
<br />
#Html.CheckBoxFor(w => w.UseWindowsAuthentication, new { #checked = "checked" }) Use Windows Authentication<br /><br />
<div class="wizard-sqlauth" style="display: none">
<div class="input-group">
<span class="input-group-addon">User name</span>
#Html.TextBoxFor(w => w.UserName, new { #class = "form-control", placeholder = "User name" })
</div>
#Html.ValidationMessageFor(w => w.UserName)<br />
<div class="input-group">
<span class="input-group-addon">Password</span>
#Html.PasswordFor(w => w.Password, new { #class = "form-control" })
</div>
#Html.ValidationMessageFor(w => w.Password)
</div>
DatabaseName is "Required" and your input is empty. (There is only placeholder text)
Are you calling jquery validation "manually" anywhere in javascript, i.e.
$('#myform').valid() ?
That would trigger the default value for the required rule ("This field is required."), and would append it as a label after the input, which is exactly the behavior your are experiencing.
If you really need to use both (MVC's Unobstrusive validation + jQuery validation) you can configure jquery validation to ignore certain fields, for example
$('#myform').validate({
ignore: '#databasefieldId'
});
You have applied the RequiredAttribute attribute to a property to the property DatabaseName which implies that the property must contain a value.
A validation exception is raised if the property is null, an empty string (""), or contains only white-space characters.
You just add #Html.ValidationMessageFor(w=> w.DatabaseName) in the top of div. This will show the summary.
Where the heck are these things coming from? I like them, and I would like to leverage them elsewhere in my site. It appears they only show when I do regular expression validation in model:
[Display(Name = "Residential")]
[RegularExpression(#"[-+]?[0-9]*\.?[0-9]?[0-9]", ErrorMessage = "Must be a number")]
public Byte? residentialExperience { get; set; }
<div class="editor-label row">
#Html.LabelFor(model => model.residentialExperience)
</div>
<div class="editor-field row">
#Html.EditorFor(model => model.residentialExperience)
#Html.ValidationMessageFor(model => model.residentialExperience)
</div>
How can I use these validation tooltips elsewhere? Also, how can I turn them off?
Also: It's not displaying the same message as I have in my model. It says, "Please enter a number" whereas I have written "Must be a number."
This is because you are outputting a numeric field. If you look at your HTML you will see that you have something like this:
<input type="number" ... />
By defining the type as a numbber, the browser knows what to expect and it will give you a generic message. This is part of Html 5 spec.
If you want to override the default behavior you could do this:
#Html.TextBoxFor(model => model.residentialExperience, new { #type = "text" })