0
我在我的模型中有一个变量Datetime类型,我试图用html助手在视图中显示它。我这样做从控制器传递日期时间到视图
@Html.TextBoxFor(model => model.dated, new {required = "required", type="date" }
但输入不带任何价值
我在我的模型中有一个变量Datetime类型,我试图用html助手在视图中显示它。我这样做从控制器传递日期时间到视图
@Html.TextBoxFor(model => model.dated, new {required = "required", type="date" }
但输入不带任何价值
下面是一个简单的工作示例:
@model SimpleTest.Controllers.SimpleViewModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Test</title>
</head>
<body>
<div>
@using (Html.BeginForm()) {
// Use whatever format string that suits your purposes:
@Html.TextBoxFor(model => model.Dated, "{0:d MMM yyyy}")
<input type="submit" value="Submit value"/>
}
</div>
</body>
</html>
而且现在的控制器代码(只是用于验证解决方案的缘故):
using System;
using System.Web.Mvc;
namespace SimpleTest.Controllers {
public class DateController : Controller {
public ActionResult Index(SimpleViewModel model) {
// First time you visit the page, there is no view data
// (model.Dated will be equal to DateTime.MinValue) so we set
// the date to "now".
//
// When you submit data through the form in the view and henceforth,
// the value of model.Dated will be resolved from view data,
// and we simply pass it back to the view again so that the result is
// visualized.
var date = model.Dated == DateTime.MinValue
? DateTime.Now
: model.Dated;
return View(new SimpleViewModel {
Dated = date
});
}
}
public class SimpleViewModel {
public DateTime Dated { get; set; }
}
}
如果您尝试编辑文本框中的日期值,您会发现t它会被默认的模型绑定器正确解析并传递给控制器中的操作。
我不知道html.textboxfor的第二个参数可以用来设置格式。我通过不使用助手解决了问题,但解决方案更好。谢谢 – AnotherGeek 2014-10-08 13:38:25
使用DateTime.ToString()重载之一(例如DateTime.ToString(String,IFormatProvider))。或者可能更合适 - 将日期格式化为已存在于控制器中的本地化字符串,并将其传递给视图(通过视图模型)。 – 2014-10-08 11:25:57
试试这个回答http://stackoverflow.com/a/7026781/492258 – 2014-10-08 11:27:38
在源代码中,我看到输入的值是这样设置的value =“09/12/2025 23:00:00”,I知道它应该是这个值=“2014-10-10”。我不知道如何解决我的问题,我在帮手中添加了值=“2014-10-10”,但这并没有帮助 – AnotherGeek 2014-10-08 11:29:48