我如何传递日期时间,例如01/01/2011 21:01:34作为查询字符串?
我正在建立一个剧院预订网站,当我观看表演时,我目前通过了演出和场地,但也需要通过日期(因为这是演出的独特部分)
ActionResult看起来像这样:
public ActionResult Details(String name, String venue, String date)
{
return View(_repository.performanceDetails(name, venue, date));
}
Run Code Online (Sandbox Code Playgroud)
但是performanceDate不会工作,因为它是一个日期时间数据类型!我需要做的是删除数据的时间部分,例如00:00:00并以某种方式将剩余数据作为字符串传递,我可以用它来比较,如下所示:
public PerformanceDetails performanceDetails(String name, String venue, String date)
{
var PerformanceDetails = (from s in _db.PerformanceDetails
where s.show == name &&
s.venue == venue &&
s.performanceDate == date
select s).First();
return PerformanceDetails;
}
Run Code Online (Sandbox Code Playgroud)
这是一个示例链接:
<%= Html.ActionLink("View Details", "Details", "Performances",
new {
name = item.show,
venue = item.venue,
date = item.performanceDate },
new {@class = "button"}) %>
Run Code Online (Sandbox Code Playgroud)
首先,Action方法的参数应该是DateTime类型,而不是字符串.您应确保使用ISO 8601扩展格式(http://en.wikipedia.org/wiki/ISO_8601)格式化查询字符串参数,例如:2011-10-17T12:35:00.
默认绑定器会将该字符串转换为没有任何问题的日期.我发现你需要两个数字用于hh:mm:ss,也就是说,对于10以下的数字使用前导零.您可以省略毫秒数和时区"Z"说明符.
既然您有完整的日期和时间,您只需使用日期部分使用mydate.Date进行数据库查找.
尝试以如下格式将日期放在查询字符串上:
item.performanceDate.ToString("dd-MMM-yyyy")
Run Code Online (Sandbox Code Playgroud)
这会给你一个类似的 URL(如果你不使用路由):
http://foo/Performance/Details?name=someName&venue=someVenue&date=31-Mar-2011
Run Code Online (Sandbox Code Playgroud)
这很有用,因为您希望避免查询字符串中的日期出现斜杠,并且您希望明确月份/日期的位置(整个美国和英国)。建议使用数字表示日期,使用字母字符表示月份。
在您的 ActionMethod 中,您可以简单地TryParse()或Parse()传入的值。
var dt = DateTime.Parse(date);
Run Code Online (Sandbox Code Playgroud)
在 LINQ 查询中,您可以执行以下操作:
&& s.performanceDate == dt
Run Code Online (Sandbox Code Playgroud)
所以把它们放在一起:
public ActionResult Details(String name, String venue, String date)
{
DateTime dt;
if (DateTime.TryParse(date, out dt))
{
return View(_repository.performanceDetails(name, venue, dt));
}
else
{
return View("Error", "The value passed in date isn't a date value.");
}
}
public PerformanceDetails performanceDetails(String name, String venue, DateTime dt)
{
var PerformanceDetails = (from s in _db.PerformanceDetails
where s.show == name &&
s.venue == venue &&
s.performanceDate == dt.Date
select s).First();
return PerformanceDetails;
}
<%= Html.ActionLink("View Details", "Details", "Performances",
new { name = item.show ,
venue = item.venue,
date = item.performanceDate.ToString("dd-MMM-yyyy") },
new {@class = "button"}) %>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10196 次 |
| 最近记录: |