gpt4 book ai didi

asp.net-mvc - 在 ASP.NET MVC 中的查询字符串中创建带有日期时间的 ActionLink

转载 作者:行者123 更新时间:2023-12-03 02:12:20 24 4
gpt4 key购买 nike

我有一个搜索表单,其中包含日期时间搜索条件以及其他一些条件:

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

所以我有一个带有默认操作(我们称之为索引)和一个 SearchCriteria 参数的搜索 Controller 。

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 源代码并删除从 RouteParsedRoute 的所有违规类的代码,以创建您自己的 RouteBase 实现满足您的需要。

如果我绝对必须将 DateTime 声明保留在 SearchCriteria 类上,那么这就是我会选择的路线(抱歉是双关语)。

但是,一个更简单的解决方案是更改您的 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 或更改所有代码以使用 .Value.Member

关于asp.net-mvc - 在 ASP.NET MVC 中的查询字符串中创建带有日期时间的 ActionLink,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2022412/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com