7

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.

1 Answer 1

3

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; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I like this approach a lot, I have accepted it as an answer as it works a little bit cleaner than my solution (no messing about with bindings)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.