0

This is my Model

public class PersonVModel
{
    [Required]
    public string FirstName { get; set; }

    [Required]
    [DataType(DataType.DateTime)]
    public DateTime BirthDate { get; set; }
}

and here is my JSON

{
    "FirstName": "Artur",
    "BrithDate": "4/22/1991"
}

The strings, bools, and integers bind's well, but DateTime don't enter image description here

I have tried with [DataType(DataType.Date)] attribute too, it doesn't work too.

Any solutions?

4
  • 6
    Is the spelling mistake in the json a simple question rewrite error or actually there? Commented Dec 19, 2014 at 12:12
  • It is also likely you'll have to implement a custom model binder and tell it how to parse that very localized date format. Commented Dec 19, 2014 at 12:13
  • That's not a valid Json date. Commented Dec 19, 2014 at 12:14
  • 4/22/1991 is not a valid json date. Commented Dec 19, 2014 at 12:17

2 Answers 2

3

You have a typo : "BrithDate" vs "BirthDate"

By default MVC model binder just sets properties to default values when binding fails. You can check model validity with IsValid property.

We created special filter which throws exception with the information where binding failed. It helps a lot with AngularJS and mistypings.

public class RequireValidModel : ActionFilterAttribute
{
    /// <summary>
    /// Called by the ASP.NET MVC framework before the action method executes.
    /// </summary>
    /// <param name="filterContext">The filter context.</param>
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ModelStateDictionary state = filterContext.Controller.ViewData.ModelState;

        if (!state.IsValid)
        {
            var perPropertyMessages = state.Where(kvp => kvp.Value.Errors.Count > 0)
                                           .Select(kvp =>
                                               new
                                               {
                                                   Property = kvp.Key,
                                                   Value = kvp.Value.Value != null ? kvp.Value.Value.AttemptedValue: null,
                                                   ErrorMessages = kvp.Value.Errors.Select(err => err.Exception != null ? err.Exception.Message : err.ErrorMessage)
                                               })
                                           .Select(propertyErrors =>
                                               new
                                               {
                                                   propertyErrors.Property,
                                                   propertyErrors.Value,
                                                   ErrorMessages = string.Join("\n", propertyErrors.ErrorMessages)
                                               })
                                           .Select(
                                               propertyErrors =>
                                                   string.Format("(property: {0}, attempted value: {1}, errors: {2}\n)", propertyErrors.Property,
                                                       propertyErrors.Value, propertyErrors.ErrorMessages));

            var finalMessage = string.Format("Invalid model state:\n{0}", string.Join(",\n", perPropertyMessages));

            throw new InvalidOperationException(finalMessage);
        }
    }
}

Next, to avoid problems with dates, convert all date strings to Date objects at the very place where data is received.

Sign up to request clarification or add additional context in comments.

Comments

3

Your Json contains a US-specific date string, which is why it isn't recognized as a valid date. This string would also cause issues with any C# code that didn't run with a US locale.

While JSON itself doesn't specify a date type, everyone nowadays uses Javascript's ISO8601 format, eg: "2012-04-21T18:25:43-05:00Z"

4 Comments

Not necessarily only javascript's iso format - it's a fairly language agnostic standard. =)
Didn't say it is. But people did end up adopting Javascript's format instead of the initial attempts to use a unix timestamp-like format
Oh! I managed to parse the grammar now. Silly Anglosisms. My mistake.
No, just speed typing while also trying to work. I had to read the sentence myself twice

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.