I have a variable in my model of type Datetime, I am trying to display it in the View with the html helper. I did this
@Html.TextBoxFor(model => model.dated, new {required = "required", type="date" }
but the input does not take any value
I have a variable in my model of type Datetime, I am trying to display it in the View with the html helper. I did this
@Html.TextBoxFor(model => model.dated, new {required = "required", type="date" }
but the input does not take any value
Here is a simple working example:
@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>
And now the controller code (just for the sake of verifying the solution):
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; }
}
}
If you try editing the date value in the text box, you will find that it is properly resolved by the default model binder and passed to the action in the controller.