在asp.net mvc中看起来像日期的binder在工作上不正确 [英] Looks like binder for date works incorrect in asp.net mvc

查看:164
本文介绍了在asp.net mvc中看起来像日期的binder在工作上不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有在QueryString中的startdate值为:3/1/2012



DateTime.Parse(Request.QueryString [startdate])。月份返回月份号:1



但在我的控制器中我有动作索引(DateTime startDate)和startDate.Month返回3



有人可以解释为什么绑定的日期不按预期工作?



btw,我有web.config文化已经:

 < worldwide uiCulture =en-GBculture =en-GB/> 


解决方案

默认模型binder 始终在解析查询字符串值时使用InvarianCulture,无论您在web.config中配置了哪种文化。




  • GET => InvariantCulture

  • POST =>文化不可知



所以假设你有两个动作:

  [HttpGet] 
public ActionResult Foo(DateTime date)
{
...
}

[HttpPost]
public ActionResult Bar(DateTime date)
{
...
}
/ pre>

当您调用Foo操作时,您应该始终使用不变文化格式化查询字符串中的日期,而在调用Bar操作并传递日期时参数在POST主体有效负载中,默认模型绑定将使用您的web.config中配置的文化。



查看以下博客文章,其中详细介绍了这一点。


I have startdate in QueryString with value: 3/1/2012

DateTime.Parse(Request.QueryString["startdate"]).Month return month number: 1

but in my controller i have action Index(DateTime startDate) and startDate.Month return 3

Is anybody can explain why bind of date doesnt work as expected?

btw, i have culture in web.config already:

<globalization uiCulture="en-GB" culture="en-GB"/>

解决方案

The default model binder always uses InvarianCulture when parsing query string values, no matter which culture you configured in your web.config.

  • GET => InvariantCulture
  • POST => culture agnostic

So assuming you have the 2 actions:

[HttpGet]
public ActionResult Foo(DateTime date)
{
    ...
}

[HttpPost]
public ActionResult Bar(DateTime date)
{
    ...
}

when you invoke the Foo action you should always use the invariant culture to format the date in the query string, whereas when you invoke the Bar action and pass the date parameter in the POST body payload, the default model binder will use the culture configured in your web.config.

Take a look at the following blog post which covers this in more details.

这篇关于在asp.net mvc中看起来像日期的binder在工作上不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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