首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >没有为Json请求执行ModelBinder

没有为Json请求执行ModelBinder
EN

Stack Overflow用户
提问于 2014-04-23 18:32:02
回答 1查看 105关注 0票数 0

这是我的模型活页夹

代码语言:javascript
复制
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;
}

下面是我如何在Global.asax中注册它

代码语言:javascript
复制
ModelBinders.Binders[typeof(DateTime)] = new DateTimeModelBinder();

下面是我的TestModel类的样子

代码语言:javascript
复制
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; }
}

当我导航到我的Controller/Action MyTest时,我能够调用我的ModelBinder类。因此,下面的工作

代码语言:javascript
复制
public ActionResult MyTest()
{
    var model = new TestModel {LastModified = DateTime.UtcNow, LastModifiedNullable = DateTime.UtcNow};
    return View("MyTest1", model);
}

但是,当我导航到我的Controller/Action请求时,我的ModelBinder类代码不会被调用。最终,我希望能够将Json请求日期转换为UTC日期时间。

代码语言:javascript
复制
public ActionResult MyTestJsonB()
{
    var myTestModel = new TestModel
        {
            LastModified = DateTime.UtcNow,
            LastModifiedNullable = DateTime.UtcNow,
            TheStrinDateTime = "hello"
        };

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

问题:当我调用请求MyTestJsonB时,如何调用ModelBinder类。它完全绕过它。--

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-04-23 22:14:03

首先,我认为你应该像这样注册你的custom BinderModelBinders.Binders.Add(typeof(DateTime), new DateTimeModelBinder());

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23252484

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档