从自定义模型活页夹中调用默认模型活页夹吗? [英] Call Default Model Binder from a Custom Model Binder?

查看:98
本文介绍了从自定义模型活页夹中调用默认模型活页夹吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个自定义模型绑定器,该绑定器应该根据当前区域性映射来自URL字符串(GET)的日期(此处的旁注:如果您使用GET作为默认模型绑定器,则不会考虑当前区域性http-call ...).

I have written a Custom Model Binder which is supposed to map Dates, coming from URL-Strings (GET) according to the current culture (a sidenote here: the default model binder does not consider the current culture if you use GET as http-call...).

public class DateTimeModelBinder : IModelBinder
{

    #region IModelBinder Members
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {

        if (controllerContext.HttpContext.Request.HttpMethod == "GET")
        {
            string theDate = controllerContext.HttpContext.Request.Form[bindingContext.ModelName];
            DateTime dt = new DateTime();
            bool success = DateTime.TryParse(theDate, System.Globalization.CultureInfo.CurrentUICulture, System.Globalization.DateTimeStyles.None, out dt);
            if (success)
            {
                return dt;
            }
            else
            {
                return null;
            }
        }

        return null; // Oooops...

    }
    #endregion
}

我在global.asax中注册了模型联编程序:

I registered the model binder in global.asax:

ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeModelBinder());

现在问题出现在最后一个return null;中.如果我在POST中使用其他形式,它将用null覆盖已经映射的值.如何避免这种情况?

Now the problem occurs in the last return null;. If I use other forms with POST, it would overwrite the already mapped values with null. How can I avoid this?

任何输入的Thx. sl3dg3

Thx for any inputs. sl3dg3

推荐答案

好吧,这实际上是一个简单的解决方案:我创建了默认活页夹的新实例并将任务传递给他:

Well, it is actually a trivial solution: I create a new instance of the default binder and pass the task to him:

public class DateTimeModelBinder : IModelBinder
{

#region IModelBinder Members
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{

    if (controllerContext.HttpContext.Request.HttpMethod == "GET")
    {
        string theDate = controllerContext.HttpContext.Request.Form[bindingContext.ModelName];
        DateTime dt = new DateTime();
        bool success = DateTime.TryParse(theDate, System.Globalization.CultureInfo.CurrentUICulture, System.Globalization.DateTimeStyles.None, out dt);
        if (success)
        {
            return dt;
        }
        else
        {
            return null;
        }
    }

    DefaultModelBinder binder = new DefaultModelBinder();
    return binder.BindModel(controllerContext, bindingContext);

}
#endregion
}

这篇关于从自定义模型活页夹中调用默认模型活页夹吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆