在这里,编写自定义模型活页夹似乎是一个好主意:
public class TimeSpanModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".TotalMinutes");
int totalMinutes;
if (value != null && int.TryParse(value.AttemptedValue, out totalMinutes))
{
return TimeSpan.FromMinutes(totalMinutes);
}
return base.BindModel(controllerContext, bindingContext);
}
}
并将其注册到
Application_Start
:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
ModelBinders.Binders.Add(typeof(TimeSpan), new TimeSpanModelBinder());
}
最后,在您的视图中总是更喜欢强类型的帮助程序:
<% using (Html.BeginForm()) { %>
<%= Html.EditorFor(x => x.Interval) %>
<input type="submit" value="OK" />
<% } %>
~/Views/Home/EditorTemplates/TimeSpan.ascx
):
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<TimeSpan>" %>
<%= Html.EditorFor(x => x.TotalMinutes) %>
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Interval = TimeSpan.FromDays(1)
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// The model will be properly bound here
return View(model);
}
}