Here is my model to format the date based on the current culture.
I tried to avoid hard coding like DataFormatString = "{0:MM/dd/yyyy}"
The reason for doing below is to get the current culture pattern
[Required(ErrorMessage = "Date is required")]
[DisplayFormat(ApplyFormatInEditMode = true,
DataFormatString = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern.ToString())]
[Display(Name = "Date", ResourceType = typeof(Resources.Global))]
public DateTime Date { get; set; }
and in .cshtml
#Html.TextBox("Date",
Model.Date.ToString("d", System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat), new { #class = "datePicker" })
Issue: I am getting an error
An attribute argument must be a constant expression, typeof
expression or array creation expression of an attribute parameter type
Is there way to show a current culture based short date in MVC TextBox Helper?
{0:d} is the current culture ShortDatePattern,
instead of
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern.ToString())]
You should use
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = {0:d})]
Having set that, DataFormatString is only used in EditorFor and DisplayFor. So you should change your view to
#Html.EditorFor(model => model.Date, new { #class = "datepicker" })
Remember to add #model YourModel at the top of the view
Related
I am trying to load today's date into the HTML5 date input type in Core 1.1, however when I set today's date in the controller, I get the following error in the console on the page.
The specified value "9/3/2017 12:00:00 AM" does not conform to the required format, "yyyy-MM-dd".
AddWorkOrder.cshtml
<div class="form-group">
<b>Issue Date:</b>
#Html.TextBoxFor(Model => Model.NewWorkOrder.workOrderIssueDate, new { #class = "form-control", #type = "date", #value = Model.NewWorkOrder.workOrderIssueDate.ToString("yyyy-MM-dd") })
#Html.ValidationMessageFor(Model => Model.NewWorkOrder.workOrderIssueDate, "", new { #class = "valColor" })
</div>
WorkOrderController.cs
// GET : /WorkOrder/AddWorkOrder
public IActionResult AddWorkOrder()
{
WorkOrderViewModel workOrderVm = new WorkOrderViewModel();
using (var db = new WorkOrderDBContext())
{
workOrderVm.NewWorkOrder = new WorkOrder();
workOrderVm.NewWorkOrder.workOrderIssueDate = DateTime.Today;
}
return View(workOrderVm);
}
I have tried setting the value of the textbook to be #value = DateTime.Today.ToString("yyyy-MM-dd") and that does not load the date either.
You can use data-format attribute like this for post correct format date:
#Html.TextBoxFor(Model => Model.NewWorkOrder.workOrderIssueDate, "{0:yyyy-MM-dd}", new { #class = "form-control", #type = "date" })
I was having a very similar problem but I had a clue because I had two dates on my input form and one was working while the other wasnt. I got very confused because the HTML and the Razor markup was exactly the same. Then I noticed that for the date that wasnt working as expected, I decorated the attribute in the model wtih
[DataType(DataType.Date)]
but for the value that worked correctly I decorated that as
[DataType(DataType.DateTime)]
Once I changed them both to be DateTime, the error went away. I don't pretend to understand why.
I am using Entity framwork 6 , MVC 4 and jquery datepicker. When fill all the form data and press the submit button the ModelState.IsValid always return false value, because the jquery datepicker value not match with the model validation field.
in .cshtml file
-----
-----
#Html.TextBoxFor(m => m.Annieversary, new { id = "anudate", #class = "form-control datetimepicker", #placeholder = "Annieversary Date" })
-----
-----
c# Side
[Required(ErrorMessage = "This field is required")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date, ErrorMessage = "Date required")]
public Nullable<System.DateTime> Annieversary { get; set; }
I tried below
#Html.TextBoxFor(m => m.Annieversary,"{0:dd/MM/yyyy}", new { id = "anudate", #class = "form-control datetimepicker", #placeholder = "Annieversary" })
This is also not match with the model, always return null value. I know c# only accept the "MM/DD/YYYY" format but jquery datepicker return "DD/MM/YYYY" format. How can I solve this problem?
First of all, let's simplify so it can work. Then you can add the attributes you feel you need.
Model
Notice that I am using the question mark to make the field nullable - as I understand you will need it:
public DateTime? Anniversary { get; set; }
View
Notice the datepicker class, which we will use to call the jQuery UI DatePicker component:
#Html.TextBoxFor(m => m.Anniversary, new { #class = "datepicker" })
JavaScript
Notice that I am setting the dateFormat to the format you need. That helps but it's not enough just yet:
<script>
$(function () {
$(".datepicker").datepicker({ dateFormat: "dd/mm/yy" });
});
</script>
Web.Config
Now, here is where the magic happens. You need to set the culture of your application in order to have the proper date format. I have it set to pt-BR, which gives the same date format you need:
<globalization culture="pt-BR" uiCulture="pt-BR"/>
That should do it, but it's the most basic example.
The most important thing to remember is: The date format should always match the culture you set in the web.config.
I have a view that has two input fields that are bound to a DateTime and a DateTime? (nullable DateTime) model property.
<div class="form-group">
#Html.LabelFor(model => model.EffectiveDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EffectiveDate, new { htmlAttributes = new { id = "txtEffectiveDate", Value = Model.EffectiveDate.ToString("MM/dd/yyyy"), #class = "form-control " } })
#Html.ValidationMessageFor(model => model.EffectiveDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CancelDate, htmlAttributes: new {#class = "control-label col-md-2"})
<div class="col-md-10">
#Html.EditorFor(model => model.CancelDate, new {htmlAttributes = new {id = "txtCancelDate", #class = "form-control " } })
#Html.ValidationMessageFor(model => model.CancelDate, "", new {#class = "text-danger"})
</div>
</div>
Here's the two properties of the Model:
public class Edit
{
[Display(Name = "Effective Date")]
[Required(ErrorMessage = "{0} is required")]
public DateTime EffectiveDate { get; set; }
[Display(Name = "Cancel Date")]
[NotEqualTo("EffectiveDate")]
[IsGreaterThan(otherProperty:"EffectiveDate", ErrorMessage = "{0} must be after {1}")]
[Required(ErrorMessage = "{0} is required")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true, NullDisplayText = "")]
public DateTime? CancelDate { get; set; }
--etc
}
Both fields are required, so I originally did not see a need for a Nullable DateTime data type. However, I'm finding that if I were to use the DateTime data type, I am getting unexpected behavior.
For example, if the user types in 11/32/2016 for either the Effective or Cancel Date fields, a client side validation error is displayed "The field Effective Date must be a date" and "The field Cancel Date must be a date." However, if the user types in 11/31/2016 for both values, the property attribute-driven client side validation does not catch this and the invalid dates are posted to the server as 1/1/0001 for the regular not nullable EffectiveDate property's value and NULL for the nullable CancelDate property. I was disappointed in this apparent shortcoming in what I would have expected to be a basic common edit, but things get worse when we post to the controller method...
Since client side validation logic wasn't good enough to catch on the client that 11/31/2016 was not a valid date, it seems reasonable to me that since the EffectiveDate is a DateTime, it must be assign some value and 1/1/0001 seemed like a reasonable choice. Furthermore, since CancelDate was nullable, null is posted, as expected.
In my controller, I check if the ModelState is invalid.
[HttpPost]
[ActionName("Edit")]
public ActionResult Edit(ViewModels.Edit modifiedAssessment)
{
if (!base.ModelState.IsValid)
{
return this.View(modifiedAssessment);
}
The ModelState contains two errors which are displayed next to their associated input fields:
The value '11/31/2017,07/22/2016 12:30:08' is not valid for Effective Date.
The value '11/31/2017' is not valid for Cancel Date.
Another issue:
Why are two dates, 11/31/2017 and 7/22/2016 (today), part of the error message for EffectiveDate?
Another troubling part is troubling part is that the Dates that now appear in the EffectiveDate and CancelDate input fields are now 01/01/0001 and 11/31/2017, respectively. Note that 11/31/2017 is not a valid value for either a dateTime or a DateTime? data type, yet the nullable CancelDate property did not wipe out the originally typed value but the EffectiveDate DateTime value did.
Given this behavior, how can anyone use the DateTime datatype for model binding? I tried to add the following attribute to the EffectiveDate DateTime property
[DataType( DataType.Date)]
but this opens up a large can of worms when I consider all of the browsers that may be using the web app.
It seems like I must be missing something basic since surely binding us a DateTime should be very common. I'm brand new to MVC.
I've read up on several posts with similar problems but still I can't get it to work properly. My problem is formating two timespan properties to mm:ss, and having them work with this bootstrap datepicker correctly.
The model properties: (Not sure if it's correct)
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = #"{0:mm\:ss}")]
public TimeSpan AgentHoldoffTime { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = #"{0:mm\:ss}")]
public TimeSpan AgentAlertTime { get; set; }
public InteractionQueueModel() // ctor
{
AgentAlertTime = new TimeSpan(0, 0, 17);
AgentHoldoffTime = new TimeSpan(0, 2, 00);
}
The view:
#Html.EditorFor(model => model.QueueModel.AgentHoldoffTime, new { htmlAttributes =
new { #class = "form-control timepicker-holdOffTime" } })
#Html.EditorFor(model => model.QueueModel.AgentAlertTime, new { htmlAttributes =
new { #class = "form-control timepicker-alertTime" } })
JS:
var timePickerAlertTime = $(".timepicker-alertTime"),
timePickerHoldOffTime = $(".timepicker-holdOffTime");
timePickerAlertTime.datetimepicker({
format: "mm:ss",
})
.on("dp.change", function () {
...
});
timePickerHoldOffTime.datetimepicker({
format: "mm:ss",
})
.on("dp.change", function () {
...
});
Now, when the view renders, a textbox displays 00:17 for a time(7) column with the value 00:00:17.0000000. Everything seems fine, But when I submit 01:00 it's saved as 01:00:00.0000000 instead of 00:01:00.0000000? I've probably missed something simple, but I can't figure it out.
Thanks in advance.
specifying the format works for me:
#Html.TextBoxFor(m => Model.AgentHoldoffTime,
"{0:hh\\:mm}",
new {
#class = "form-control",
placeholder = "hh:mm",
})
this signature:
//
// Summary:
// Returns a text input element.
//
// Parameters:
// htmlHelper:
// The HTML helper instance that this method extends.
//
// expression:
// An expression that identifies the object that contains the properties to display.
//
// format:
// A string that is used to format the input.
//
// htmlAttributes:
// An object that contains the HTML attributes to set for the element.
//
// Type parameters:
// TModel:
// The type of the model.
//
// TProperty:
// The type of the value.
//
// Returns:
// An input element whose type attribute is set to "text".
public static MvcHtmlString TextBoxFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
string format,
object htmlAttributes);
When you use 'EditorFor' the Framework try to render the best HTML element for the data type, in case of TimeSpan, the best is an <input type="time"/>, as i understand you need handle seconds, but this input by default does not consider seconds, you'll need to "force" with attribute step = 1. Now if you use 'EditorFor' it does not allows you to set attributes, or at least i have not found how to do that, so changes it to 'TextBoxFor':
#Html.TextBoxFor(model => model.AgentHoldoffTime, new
{
#class = "form-control timepicker-holdOffTime",
type = "time",
step = 1
})
I Hope this help
I want to know how can I convert a strong typed view Price field in to 2 digit specifier like i have got a money field in my db which converts for instance 15 into 15.0000 , i juts want to display 15.00 in the view , below is the code:
<%: Html.TextBoxFor(model =>model.Price, new { maxlength = "5", style = "width:40px;" })%>
I tried something like with no success:
<%: Html.TextBoxFor(model => String.Format("{0:n}"model.Price), new { maxlength = "5", style = "width:40px;" })%>
You can put an attribute on the model something like:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:n}")]
If you don't want to do that then you will need to use the 'old' style text box:
<%= Html.TextBox("Price", string.Format("{0:n}", Model.Price)) %>
Try this:
<%: Html.TextBoxFor(model => model.Price.ToString("0.00"), new { maxlength = "5", style = "width:40px;" })%>
Update:
You also missed a comma in your original syntax which could be all that's stopping it from working that way too. Should have been:
<%: Html.TextBoxFor(model => String.Format("{0:n}", model.Price), new { maxlength = "5", style = "width:40px;" })%>
Also, for 2 decimal places, try it like this:
<%: Html.TextBoxFor(model => String.Format("{0:0.00}", model.Price), new { maxlength = "5", style = "width:40px;" })%>
Your best bet is to use a DataAnnotations display format attribute on your view model. Something like this:
[DisplayFormat(DataFormatString = "{0:n}")]
And then use the Html.EditorFor(model => model.Price) to render the input.
Have you tried using mode.Price.ToString() and specifying your desired format string in the ToString method?
this may help.
private DateTime hDay;
[DisplayName("Hire Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime HireDate
{
get
{
if (hDay == DateTime.MinValue)
{
return DateTime.Today;
}
else
return hDay;
}
set
{
if (value == DateTime.MinValue)
{
hDay = DateTime.Now;
}
}
}
OR
we can use this way too
#Html.TextBoxFor(m => m.MktEnquiryDetail.CallbackDate, "{0:dd/MM/yyyy}")