Call Default Model Binder from a Custom Model Binder?

杀马特。学长 韩版系。学妹 提交于 2019-12-07 05:42:32

问题


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
}

I registered the model binder in global.asax:

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

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 for any inputs. sl3dg3


回答1:


Derive from DefaultModelBinder and then invoke the base method:

public class DateTimeModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        // ... Your code here

        return base.BindModel(controllerContext, bindingContext);
    }

}



回答2:


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
}


来源:https://stackoverflow.com/questions/6411993/call-default-model-binder-from-a-custom-model-binder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!