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
Related
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.
I have a simple date field that i want to populate with a value from my database so my users can see the default before they edit:
<input type = "date" name = "Date" style = "width:180px;" value="#ViewBag.Options.Date"/>
Simply put, this doesnt popluate the date input. it works on all other forms of html5 inputs however, also worth noting that the ViewBag.Options.Date is a DateTime variable.
Your date needs to have a specific formatting to make it unambiguous:
#ViewBag.Options.Date.ToString("yyyy-MM-dd")
For every HTML input field, the browser will leave it empty unless a default value is specified with the value attribute.
currently HTML5 doesn't provide any way of specifying default date in the value attribute.
try some script may be it helps.
In the web app I'm working on, the web app should be able to accept null DateTimevalues, because customers might be hesitant to give information about their Date of Birth. Of course, this won't be an easy task, because in C#, DateTime is not nullable.
DateTime rawBirthDate = Convert.ToDateTime(txtDOB.Text);
fxTxn.BirthDate = rawBirthDate;
with that, I had to change my code to accept a null value:
DateTime? rawBirthDate = string.IsNullOrEmpty(txtBirthDate) ? (DateTime?)null : DateTime.Parse(txtBirthDate);
fxTxn.BirthDate = Convert.ToDateTime(rawBirthDate);
this code, in turn, returns 1/1/0001 12:00:00.000 AM. However, MSSQL throws a DateOutOfRangeException, saying the date must be between 1/1/1753 and 12/31/9999.
I'm completely stuck in here. On my SQL table, I allowed the BirthDate column to accept null values. Question now is, how do I make C# consider null DateTime values? The end result would be that, if the Customer did not provide Date of Birth information, the system should still be able to save the record but the BirthDate column in the customer's record would still be NULL.
What you need to do is this: your column table should accept null for BirthDate (that's correct). In C#, make the variable rawBirthDate nullable.
Now, the condition you need to check is:
rawBirthDate.HasValue
If it's true, then insert the date in db.
If false, do not insert anything in the db (that's what 'allow null' means in SQL).
how do I make C# consider null DateTime values
Your value was null. The problem is that you converted it to a standard DateTime which is giving you the DateTime.MinValue (1/1/0001)
I think the problem might be in the code that actually inserts the value into database:
...
var valueToInsert = rawBirthDate ?? DBNull.Value;
...
Why are you converting null value in datetime, if you define nullable variable then it can store null vaue. Actually you need to define BirthDate property also nullable and store null value if user have not entered date like
fxTxn.BirthDate = string.IsNullOrEmpty(txtBirthDate) ? null : DateTime.Parse(txtBirthDate);
In db you need to make that column to allow null value and check value of BirthDate like
if (fxTxn.BirthDate.HasValue)
{
// pass value in db otherwise not
}
I have a C# List with one particular column as of DateTime.
I have to bind this column to CategoryAxis of Silverlight Chart - hence looking for converting this DateTime column to String type with formatting as .ToString("dd-MMM-yy") without altering any sort order.
Any inputs?
Add one more field in list and store the string date in it using for each loop.
add one more read-only wrapper property to it, something like:
public string StrDT
{
Get
{
return myDateTime.ToString("dd-MMM-yy");
}
}
then bind this field to wherever you like...
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; }