最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Safe way to pass a date param to an ajax call to a MVC action - Stack Overflow

programmeradmin7浏览0评论

I have a MVC action that takes one of its parameters a DateTime and if I pass "17/07/2012" it throws an exception saying that the param is null but cannot have a null value but if I pass 01/07/2012 it is parsed as Jan 07 2012.

I'm passing the dates to the ajax call in DD/MM/YYYY format, should I rely on MM/DD/YYYY format despite the configured culture in web.config?

This is a simple method and there is just this one date parameter.

I have a MVC action that takes one of its parameters a DateTime and if I pass "17/07/2012" it throws an exception saying that the param is null but cannot have a null value but if I pass 01/07/2012 it is parsed as Jan 07 2012.

I'm passing the dates to the ajax call in DD/MM/YYYY format, should I rely on MM/DD/YYYY format despite the configured culture in web.config?

This is a simple method and there is just this one date parameter.

Share Improve this question edited May 10, 2012 at 5:31 gdoron 150k59 gold badges302 silver badges371 bronze badges asked May 9, 2012 at 16:00 BrunoBruno 4,52713 gold badges45 silver badges59 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

You got three safe options to send date parameter in Asp.NET-MVC:

  • Send it as YYYY/MM/DD it's the ISO standard for international dates.
  • Use POST request instead of GET request.

  • If you want to change the way the default Model Binder binds dates:

you can change the default model binder to use the user culture using IModelBinder

public class DateTimeBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        var date = value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture);

        return date;    
    }
}

And in the Global.Asax write:

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

Read more at this excellent blog that describe why Mvc framework team implemented a default Culture to all users.

gdoron's answer is correct for passing dates as querystrings. If they are passed as form values, however (post values) then the correct culture should be used (assuming the culture is property configured).

发布评论

评论列表(0)

  1. 暂无评论