dotnet-practitioner
dotnet-practitioner

Reputation: 14148

ModelBinder not being executed for Json Request

Here is my model binder

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
    if (value == null || value.AttemptedValue == "null" || value.AttemptedValue == string.Empty)
    {
        return null;
    }

    var rawDateTimeValue = (DateTime)value.ConvertTo(typeof(DateTime));
    if (!rawDateTimeValue.Equals(rawDateTimeValue.ToMinTime()))
    {
        return TimeZoneManager.GetUtcTime(rawDateTimeValue);
    }

    return rawDateTimeValue;
}

Here is how I register it in Global.asax

ModelBinders.Binders[typeof(DateTime)] = new DateTimeModelBinder();

Here is what my TestModel class look like

public class TestModel
{

    [JsonProperty(ItemConverterType = typeof(JavaScriptDateTimeConverter))]
    public DateTime LastModified { get; set; }


    [JsonProperty(ItemConverterType = typeof(JavaScriptDateTimeConverter))]
    public DateTime? LastModifiedNullable { get; set; }


    [JsonProperty(ItemConverterType = typeof(JavaScriptDateTimeConverter))]
    public string TheStrinDateTime { get; set; }
}

When I navigate to my Controller/Action MyTest, I am able to invoke my ModelBinder class. So the following works

public ActionResult MyTest()
{
    var model = new TestModel {LastModified = DateTime.UtcNow, LastModifiedNullable = DateTime.UtcNow};
    return View("MyTest1", model);
}

But when I navigate to my Controller/Action for Json request, my ModelBinder class code does not get called. Eventually, I want to be able to convert my Json request dates to UTC datetime.

public ActionResult MyTestJsonB()
{
    var myTestModel = new TestModel
        {
            LastModified = DateTime.UtcNow,
            LastModifiedNullable = DateTime.UtcNow,
            TheStrinDateTime = "hello"
        };

    return Json(myTestModel, "text/plain", JsonRequestBehavior.AllowGet);
}

Question: When I invoke the request MyTestJsonB, how do I invoke the ModelBinder class. It completely bypasses it.

Upvotes: 0

Views: 110

Answers (1)

user3383479
user3383479

Reputation:

First I think you should register your custom Binder like this: ModelBinders.Binders.Add(typeof(DateTime), new DateTimeModelBinder());

Instead of ModelBinders.Binders[typeof(DateTime)] = new DateTimeModelBinder();

Upvotes: 1

Related Questions