Time Input Field in ASP.NET MVC - asp.net-mvc-4

I'm having trouble trying to write a form with time field using ASP.NET MVC 4.
Model:
class Abcde {
[DataType(DataType.Time)]
public DateTime ATime { get; set; }
}
View.cshtml
...
#Html.EditorFor(m => m.ATime)
#Html.ValidationMessageFor(m => m.ATime)
The validation always failed when I tried to input a time (hh:nn:ss), and said it was not in the corrent format, so i have to input a date instead.
My Question is should I change the type to TimeSpan? Or is there any other way?

[Required]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:H:mm}")]
public DateTime Time { get; set; }`
Try this, you can format in the DataFormatString the way you want it to work for you, im using it in a project now and it's working for me.

Actually this is what worked for me.
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm}")]
public DateTime Hour { get; set; }

[Required]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm}")]
public DateTime Time { get; set; }
This code is correct. But it only works when you use EditorFor instead of TextBoxFor.

Use:
[Required]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm:ss}")]
public DateTime FieldTime{ get; set; }
You need to match your date validation with the format that works internally for this annotation. So, adding the ApplyFormat passing a String Pattern you can get it.

Related

How to save a time-value with EF6

I'm creating a timesheet with ASP.Net MVC.
Therefore, I need to save date values and time values in my database.
My datafields actually are type of datetime:
[Required]
public DateTime TimesheetDate { get; set; }
[Required]
public DateTime BeginOfWork { get; set; }
[Required]
public DateTime EndOfWork { get; set; }
Now, if I'd like to save a time-value of 07:30, the model to save contents something like: 01.01.0100 07:30:00
With this, the saveChanges Function fails. So how can I store times in a database, so that I could calculate later with them?
Which type of data should the field have?
Thanks Carsten

MVC4: DateTime column sorting in asp.net mvc webgrid

I have been trying to sort DateTime column in asp.net mvc webgrid.
Here is my code:
grid.Column(header: "Product Purchased Date",columnName:"PurchasedDate" canSort: true,format: #<text>
#item.PurchasedDate.ToString("MM/dd/yyy")</text>
when i tried using above code i am getting this errors:
cannot convert from 'lambda expression' to
'System.Func'
The best overloaded method match for System.Web.Helpers.WebGrid.Column(string, string, System.Func, string, bool)' has some invalid arguments.
if i apply the above code without using columName i am unable to perform sorting.
Apologize if i missed anything.
I'd recommend that, if you want to sort it as a string, add a function within your Model object that returns the value as a string instead of converting it inline. So there would be a field such as PurchasedDateAsString on the object.
For instance this is something I used in a recent project. The field DateRange is returned as a string and can be sorted upon just like it was a "base" field:
public class PeriodView
{
[Key]
public int PeriodId { get; set; }
public string Name { get; set; }
public int Number { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public int Year { get; set; }
public string Month { get; set; }
public string DateRange
{
get
{
var start = String.Format("{1}-{0}",
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(StartDate.Month).Substring(0, 3),
StartDate.Day);
var end = String.Format("{1}-{0}",
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(EndDate.Month).Substring(0, 3),
EndDate.Day);
return String.Format("{0} to {1}", start, end);
}
}
}
If you convert DateTime to string and format it, the WebGrid will sort the column as a string, which is not correct for DateTime Format Column expected result.

asp.net MVC: TryUpdateModel doesn't bind DateTime properly

I'm having issues with a date property not binding correctly using TryUpdateModel in MVC.
I am using a POCO class and a corresponding viewModel.
public class ContactModel
{
public int Id { get; set; }
[Display(Name = "First Name")]
[StringLength(50)]
[Required(ErrorMessage = "First name must be entered.")]
public string ContactGivenName { get; set; }
[Display(Name = "Last Name")]
[StringLength(50)]
[Required(ErrorMessage = "Last name must be entered.")]
public string ContactFamilyName { get; set; }
....
[Display(Name = "Date of Birth")]
public DateTime? DateOfBirth { get; set; }
}
the entity class:
public class Contact
{
[Key]
public int Id { get; set; }
[StringLength(50)]
[Column(TypeName = "varchar")]
public string ContactFamilyName { get; set; }
[StringLength(50)]
[Column(TypeName = "varchar")]
public string ContactGivenName { get; set; }
...
[Column(TypeName = "date")]
public DateTime? DateOfBirth { get; set; }
}
and in my controller :
[HttpPost]
[GridAction]
public virtual ActionResult UpdateContact(int id, FormCollection form)
{
//Find a customer whose CustomerID is equal to the id action parameter
var c = _contactService.Get(id);
if (c != null)
{
//Perform model binding (fill the customer properties and validate it).
if (TryUpdateModel(c, form))
{
The _contactService.Get returns the instance from EntityFramework.
The TryUpdateModel binds string properties like first and last name correctly, but despite a lot of tries, I can't get it to bind the date of birth.
I suspect it's a formatting issue of some kind but cannot find what it is.
When I debug, I can see in the FormCollection that the date is correctly there, with the value that was input in the view so the data is definitely passed on to the controller.
the value passed to the controller is in format :
yyyy-MM-dd
I tried modifying this on the fly with multiple format without success.
Any ideas what I'm doing wrong here ?
Thanks a lot
Well, first, I have no idea why you're using TryUpdateModel.. That's pretty archaic.
Second, it sounds to me like you have not set your culture to accept the format you expect. Add the following to your web.config if your browser is defaults already set to the correct culture:
<system.web>
<globalization culture="auto" uiculture="auto" enableclientbasedculture="true">
</globalization>
</system.web>
If you want to force a culture, then set the culture you wish in this setting.
the globalization didn't help and is actually already set, however I realized there's a custom binder for Datetime and that is probably where my problem is.
thanks

Date coming up as 12/30/1899 in MVC 4

In my model I have:
[DisplayName("Title Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = ("{0:d}"))]
public Nullable<System.DateTime> DateOfTitle { get; set; }
My View has:
<td>#Html.DisplayFor(modelItem => Model.DateOfTitle)</td>
The value in the database for this field is null. I would like the DisplayFor to show nothing unless there is a valid date for this field. It displays as 12/30/1899.
Try using this..
[DisplayFormat(NullDisplayText = "",
ApplyFormatInEditMode = true, DataFormatString = ("{0:d}"))]

Required field is not working in mvc4

in my model i have email, password,new password and re-type new password property's are there.
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email: ")]
public string Email { get; set; }
public bool changePassword { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Old Password:*")]
public string OldPassword { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "New Password:*")]
public string NewPassword { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Re-type Password:*")]
i put required to all controls.
in my view i devide those controls like, Email in one form and remaining are another form. my problem is email validation is working in form form.
coming to another form validation is not working.
can any one suggest me to come out this problem.
in your cshtml file say layout try putting this
#Scripts.Render("~/Scripts/jquery.validate.min.js")
#Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
this might work.
Make sure that you are submitting to proper controller and using the ModelState.IsValid
// POST: /Orders/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Orders order) {
if (ModelState.IsValid) {
try {
.....