ASP.NET MVC 3 Binding & Validating Date to html textbox control - c#

I have a SmallDateTime field in my Sql Server 2008 database to store users Birthdays.
On my 'Edit Profile' web page, I have a standard textbox which I want to bind the 'Birthday' date to (excluding the time as this is not required). At present I am binding to the textbox but it is rendering the full Date and Time.
In addition, when the user updates their profile, I want to be able to validate the Birthday textbox, ensuring that the value specified complies to dd/mm/yyyy, and any deviation from that is highlighted via my existing validation summary on the page.
How do I go about:
a) configuring the Birthday property in my ViewModel to display in dd/mm/yyyy format (excluding the time).
b) validate Birthday (based on dd/mm/yyyy format) when the user submits the form?

[DisplayFormat(DataFormatString="{0:dd/MM/yyyy}", ApplyFormatInEditMode=true)]
public DateTime DateOfBirth { get; set; }
This should give you the automatic formatting on the field (without you having to manually do it) and also the validation.

I usually use a string property paired with the DateTime object, something like
public string MyDateStr
{
get
{
return MyDateDate == null ? "" : MyDateDate.ToShortDateString();
}
set
{
// Usually a tryParse for the string value
}
}
I know that is not the canonical way, but up to now, is the fastest I've found.
HTH
M.
EDIT: for the validation stuff see this:other question on SO

a) you can use .ToShortDateString to render your datetime without time. Format still depends on globalization defaults.
b) to validate, you could do it with Data Annotations on your model like this:
[DataType(DataType.DateTime, ErrorMessage = "Please enter a valid date in the format dd/mm/yyyy")]
public DateTime Birthday { get; set; }

Related

Add a string property to a DateTime property

I'm building a C# object to add more strongly typed properties to a web app that accepts all of its parameters as strings. This web app displays all of a record's current values on the left, with blank fields on the right. If you leave a text input field blank, it leaves the corresponding value in the database unchanged. If you enter a new value, on submit it changes the corresponding value to the new value you entered.
In the app, date fields are entered in MM/dd/yyyy formatted strings. I have created DateTime equivilents in my C# object and use .ToString("MM/dd/yyyy") when sending them to the web app.
public DateTime NewHireDate
{
get
{
return (DateTime.TryParse(NewValue11, out dateValue) ? dateValue : DateTime.MinValue);
}
set
{
NewValue11 = value.ToString("MM/dd/yyyy");
}
}
One wrinkle is that the web app allows a user to enter "*BLANK" to essentially null out the value that's in the date field. I would like to extend that exact ability to my object by allowing the string "*BLANK" to be assigned as a value to my date property.
How would I redefine the NewHireDate property as a String so I could use myObject.NewHireDate = "*BLANK"?
As people said on the comments, u could use the type
Datetime?
instead of Datetime.
This allows you to set an Datetime property the NULL value.
You can complete this by creating methods on the class to convert these strings into DateTime format.
Reference: https://msdn.microsoft.com/en-us/library/2cf62fcy(v=vs.140).aspx

How can I sort a shortdate string as if it were a date in an MVC 5 model?

I have a field in an MVC 5 C# model that maps to an SQL table. The source data is of type nvarchar(10) for the needs of others who also use the table.
In the latest iteration, the users also want to be able to sort by this column, which means that I need to convert this to a datetime value (so it can be correctly sorted) and display as a shortdate.
I know I can make this field private and create a separate public function that casts this as a date, but I was wondering if there was a more compact way I could do this all in one function. I have searched around, but not seen any examples of what I am describing. Is this even possible?
Stated another way, I want to display this as a shortdate but sort it as a date. Am I on the right track, or am I missing something?
[Required]
[StringLength(10)]
[Display(Name = "Entry Date")]
[DisplayFormat(DataFormatString="{0:d}")]
public string EntryDate { get; set; }
If the data represents a date, add a property which is a date:
public DateTime? EntryDateValue
{
get
{
DateTime dateValue;
if (DateTime.TryParse(EntryDate, out dateValue))
return dateValue;
return null;
}
set
{
// parse "value" to the string format you want
// and store it in EntryDate
}
}
Bind the view to that property instead, formatting the output with .ToString("...") as needed, and allow the sorting to take place on the DateTime? rather than on the string. Essentially creating a pass-through property for the application code, obscuring the backing "stringly-typed" value.
In general, it's easier to tweak the correct backing data for text display than it is to tweak the text display to act like backing data.

How to handle Datetime for different ui cultures

In a web mvc5 application which supports en_Us and nb-NO cultures , How can i handle a Datetime object.
I have a ExpiryDate property in model .
How can i define the ExpDate property? What DisplayFormat i have to apply ? How can i convert that back in UI as per culture ? How can i save the data to SQlServer db as a valid datetime etc
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:DD.MM.YYYY}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> ExpDate { get; set; }
Does this helps [ which is not happening to me ]. Still confused on how to use the model in Controller and inside View while fecthing and saving data
Is any one knows some well written articles covering these aspects or any one can post some examples s\to solve this?
In general a good approach to handling these Globalization issues is to always save DateTimes as UTC on the database and also to work with UTC format at the business logic level.
In fact since you do not know until it is render time at UI which culture the user selected to see ( and not only the culture but also the time-zone ), better to stick and work with UTC values and also with a format independent approach, meaning that you should not convert the DateTime from/to string value ever anywhere else than to render in the UI or to get it from data entry form.
If you did not read anything else up to now, I would start with this article: Beginner's Tutorial on Globalization and Localization in ASP.NET MVC
or simply google by ASP.NET MVC Globalization.
good luck

Show date part only

I would like to display only the date on the page.
SQL column has type date.
Model
public System.DateTime EndDate { get; set; }
View
#Html.DisplayFor(modelItem => item.EndDate.Date)
This gives me no warnings or errors, however the time is still displaying on the page.
DateTime.Date returns a new instance of DateTime with the time component set to midnight (rather than removing the Time completely), it's only useful for normalizing date/time values and is not intended for display purposes.
Anyway, you don't need DisplayFor, you can render the date directly:
#item.EndDate.ToString("yyyy-MM-dd")
You can use theDate.ToShortDateString() or use a custom date/time string format.
The benefit of ToShortDateString() is that it is CULTURALLY SENSITIVE making your application more accessible.
If you want to use the Html.DisplayFor template helper then you may want to build a ShortDateTime.cshtml display template. Learn more about that here:
https://stackoverflow.com/a/6001836/941058
Try the ToString() date formatters:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Example:
#Html.DisplayFor(modelItem => item.EndDate.Date.ToString("MMMM dd, yyyy")

MVC2 client/server validation of DateTime/Date using DataAnnotations

The following are true:
One of my columns (BirthDate) is of type Date in SQL Server.
This very same column (BirthDate) is of type DateTime when EF generates the model.
I am using JQuery UI Datepicker on the client side to be able to select the BirthDate.
I have the following validation logic in my buddy class:
[Required(ErrorMessageResourceType = typeof(Project.Web.ValidationMessages), ErrorMessageResourceName = "Required")]
[RegularExpression(#"\b(0?[1-9]|1[012])[/](0?[1-9]|[12][0-9]|3[01])[/](19|20)?[0-9]{2}\b", ErrorMessageResourceType = typeof(Project.Web.ValidationMessages), ErrorMessageResourceName = "Invalid")]
public virtual DateTime? BirthDate
{
get;
set;
}
There are two issues with this:
This will not pass server side validation (if I enable client side validation it works just fine). I am assuming that this is because the regular expression doesn't take into account hours, minutes, seconds as the value in the text box has already been cast as a DateTime on the server by the time validation occurs.
If data already exists in the database and is read into the model and displayed on the page the BirthDate field shows hours, minutes, seconds in my text box (which I don't want). I can always use ToShortDateString() but I am wondering if there is some cleaner approach that I might be missing.
Thanks
1: This is easily solved by changing DateTime to be non-nullable, meaning the datetime value entered must be parse-able and therefore valid, and then use the:
[DataType(DataType.Date)]
attribute instead of the regular expression. This will make sure the field is required and must be parse-able.
2: This is a templating issue. The easy way is to create a custom Date.ascx template inside of /Views/Shared/EditorTemplates that calls ToShortDateString() and will hook up your jquery datepicker.
This is what mine looks like:
<%# Import Namespace="System.Web.Mvc.Html" %>
<%
string displayText = string.Empty;
if (Model != null)
{
if (DateTime.Parse(Model.ToString()) != DateTime.MinValue)
displayText = DateTime.Parse(Model.ToString()).ToShortDateString();
}
%>
<%= Html.TextBox("", displayText, new { #class = "date-box" })%>

Categories

Resources