Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dateTime object in ASP.NET MVC

Has anyone successfully bound 2 textboxes to one DateTime property using the model binding in MVC, I tried Scott's method http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx but was dissatisfied as this stops the HTML fields and Model properties having the same name (so the validation could not set the correct css if it failed).

My current attempt modifies this by removing the ValueProviderResult object from the bindingcontext and the adding a new one for the key made up from the date result and a tiem (using the .Time convention in Scotts post) but I am a little wary of messing around with the bindingContext object direct.

The idea is that i can use IDateErrorInfo and VAB PropertyComparisonValidator to compare 2 datetimes on the model where one needs to be later than the other, to do this the time element needs to be included.

like image 539
Pharabus Avatar asked Apr 07 '09 15:04

Pharabus


People also ask

What is DateTime type in C#?

DateTime is a structure that can never be null. From MSDN: The DateTime value type represents dates and times with values ranging from 12:00:00 midnight, January 1, 0001 Anno Domini, or A.D. (also known as Common Era, or C.E.) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.)

Why DateTime is a structure?

Because it is a single point. It doesn't have multiple pieces of data. Under the hood it is represented by a long. I didn't down vote, but from your answer follow that structures are always contain a single "piece of data" and this is the only reason that DateTime is the structure.

Is DateTime a struct?

DateTime is a struct . Which doesn't mean it can't have many different constructors and methods and overloads.

What is a DateTime?

The DateTime value type represents dates and times with values ranging from 00:00:00 (midnight), January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.) in the Gregorian calendar. Time values are measured in 100-nanosecond units called ticks.


1 Answers

I use a different approach and go for two different sets of models: My view model would have two properties and the validation for those fields, while my domain model would have one DateTime. Then after the binding, I let the view model update the domain:

public ActionResult Update(DateInput date)
{
    if(date.IsValid)
    {
        var domain = someRepository.GetDomainObject(); // not exactly, but you get the idea.
        date.Update(domain);
    }
    // ...
}

public class DateInput
{
    public string Date { get; set; }
    public string Time { get; set; }

    public void Update(DomainObject domain) { ... }
}

public class DomainObject
{
    public DateTime SomePointInTime { get; set; }
}
like image 123
Thomas Eyde Avatar answered Nov 15 '22 11:11

Thomas Eyde