加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 在ASP.NET MVC的查询字符串中使用DateTime创建Ac

发布时间:2020-12-16 03:32:37 所属栏目:asp.Net 来源:网络整理
导读:我有一个带有DateTime搜索条件的搜索表单,以及其他一些标准: form method="get" action="/app/search" input type="text" value="13/01/2010" name="BeginDate"/ input type="text" value="blah" name="SomeOtherCriterion"/form 所以我有一个带有默认Actio
我有一个带有DateTime搜索条件的搜索表单,以及其他一些标准:

<form method="get" action="/app/search">
    <input type="text" value="13/01/2010" name="BeginDate"/>
    <input type="text" value="blah" name="SomeOtherCriterion"/>
<form>

所以我有一个带有默认Action(让我们称之为Index)和SearchCriteria参数的Search控制器.

public class SearchController
{
    public ActionResult Index(SearchCriteria searchCriteria) {//blah }
}    

public class SearchCriteria
{
    public DateTime BeginDate {get; set;}
    public string SomeOtherCriterion {get; set;}
}

现在,如果我想创建一个ActionLink,传入一个SearchCriteria值,这样:

Html.ActionLink("Search","Index",searchCriteria)

我以美国格式获取BeginDate查询字符串参数.在Google上查看并使用Reflector在System.Web.Routing中浏览它似乎是因为它使用了InvariantCulture,所以我无能为力.

似乎没有人问过这个问题所以我猜我做的事情非常愚蠢….请帮忙!

编辑:将SearchCriteria传递给ActionLink而不是匿名对象,以显示为什么我不能自己做自定义ToString().

解决方法

鉴于该框架似乎是使用InvariantCulture来处理这一数据的硬编码,我认为您无法做很多工作来使其透明地工作.

有一个丑陋的选择 – 下载MVC源并从Route down到ParsedRoute删除所有违规类的代码,以创建自己的RouteBase实现,完成所需的操作.

如果我绝对不得不在SearchCriteria类上保留DateTime声明,那么我会选择路线(对不起双关语).

但是,一个更容易的解决方案是更改您的SearchCriteria类,使用稍微不同的DateTime字段声明,基于如下类型:

public class MyDateTime
{
  public DateTime Value { get; set; }
  //for passing MyDateTime in place of a DateTime without casting
  public static implicit operator DateTime(MyDateTime instance) { return instance.Value; }
  //so you can assign a MyDateTime from a DateTime without a cast
  //- e.g. MyDateTime dt = DateTime.Now
  public static implicit operator MyDateTime(DateTime instance) { return new MyDateTime() { Value = instance }; }
  //override ToString so that CultureInfo.CurrentCulture is used correctly.
  public override string ToString()
  {
    return Value.ToString(CultureInfo.CurrentUICulture);
  }
}

从理论上讲,你应该能够毫不费力地推出这一变化.

如果您有很多使用SearchCriteria中DateTime实例的成员(例如.Days等)的代码,那么您可能需要在MyDateTime上重现这些成员,包含内部DateTime值或将所有代码更改为使用.Value.Member.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读