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