MVC 4 models not accept jquery datapicker date format - c#

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.

Related

HTML5 input type date is not loading the date value from the controller in ASP.NET Core 1.1

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.

display a message to user if field is blank

Afternoon Folks,
I am new to c# and im trying to create an if statement to check the value of two fields and if both of these fields are blank, to then display a message to the user.
My two fields are DateofBirth with a datatype of DateTime and Age with a datatype of int. Im using studio 2013 and have a c# mvc project.
In my create.cshtml page i am using razor syntax for these two form fields.
#Html.EditorFor(model => model.client.DateOfBirth, new { htmlAttributes = new { #class = "form-control", #placeholder = "dd-mm-yyyy" } })
and
#Html.EditorFor(model => model.client.AgeNotKnown, new { htmlAttributes = new { #class = "form-control", #placeholder = "Age in Years" } })
the user needs to fill in either one or the other field when submitting the form.
In my controller and my HttpPost for the ActionResult Create. I have tried a couple of ways to get this working via an if statement but i get seem to get this to work.
I have tried using the string.IsNullOrEmpty method, but as these are DateTime and int datatypes this will not work. See sample below.
if (string.IsNullOrEmpty(clientViewRecord.client.AgeNotKnown));
{
MessageBox.Show("please an Age if DOB not known");
}
db.ClientRecords.Add(clientViewRecord.client);
db.SaveChanges();
return RedirectToAction("MainMenu", "Home");
I get three errors here:
Argument 1: cannot convert from 'int?' to 'string'
The name 'MessageBox' does not exist in the current context 3) The
best overloaded method match for 'string.IsNullOrEmpty(string)' has
some invalid arguments
The best overloaded method match for 'string.IsNullOrEmpty(string)' has
some invalid arguments
Another way i have tried to get this working is the following...
if (clientViewRecord.client.AgeNotKnown == 0 || clientViewRecord.client.DateOfBirth == 0);
{
MessageBox.Show("please enter an Age or if DOB");
}
db.ClientRecords.Add(clientViewRecord.client);
db.SaveChanges();
return RedirectToAction("MainMenu", "Home");
I get the same issue for the message box and the following for the DateofBirth filed.
Operator '==' cannot be applied to operands of type 'System.DateTime?' and 'int'
Im new to c# but think that im kinda on the right lines, i think just need a little help or any suggestions.
Regards
Betty
? means nullable whose default value will be null if i use int? its default value will be null if i use int its default value will be 0
about validation you can use ModelState for validation in MVC and add a custom validation
#Html.ValidationMessage("validation")
#Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { #class = "form-control", #placeholder = "dd-mm-yyyy" } })
#Html.EditorFor(model => model.AgeNotKnown, new { htmlAttributes = new { #class = "form-control", #placeholder = "Age in Years" } })
i used #Html.ValidationMessage("validation") which will show the validation message if i return any and in your action
if (cls.DateOfBirth == null && cls.AgeNotKnown == null)
{
ModelState.AddModelError("validation","Please select one");
return View();
}
in action it will check condition if both are null then it will return to the same view including the validation message of key validation which is defined in the view.
First of all MessageBox class is belong to windows forms. If you want to wanr the user you should use validations. I prefer jquery validation
To add control like this, just put a breakpoint to your code and look want data coming from your form. This way you can decide how do you want to control your data.
System.DateTime? and int?, this question marks tell you that these variables can be null. So you should consider that while comparing.
First of all create ViewModel for this kind of validation
public class ClientViewModel
{
[Required, DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime Date { get; set; }
[Required]
public int Age { get; set; }
}
In View
#model Models.ClientViewModel #*reference to your model usally create in Models folder*#
#Html.ValidationSummary() #* add this for validation summary displays here.*#
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control", #placeholder = "dd-mm-yyyy" } })
#Html.ValidationMessageFor(m => m.Date)
#Html.EditorFor(model => model.Age, new { htmlAttributes = new { #class = "form-control", #placeholder = "Age in Years" } })
#Html.ValidationMessageFor(m => m.Age)
#* Add jqueryval bundles which is created in app_start/BundleConfig *#
#section Scripts{
#Scripts.Render("~/bundles/jqueryval")
}
In Controller
//Change the name of PostMethod
public ActionResult PostMethod(Models.ClientViewModel model )
{
if (ModelState.IsValid)
{
// do your stuff
}
return View();
}

Basic issue binding view to a DateTime property. Better luck with DateTime nullable, but why?

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.

asp mvc format timespan (mm:ss) textboxfor to work with bootstrap timepicker

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

Model DisplayFormat's DataFormat Error in MVC3

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

Categories