我想声明类型为 TimeSpan
的 View 模型的一些属性,以显示 TotalMinutes
属性并绑定(bind)回 TimeSpan
。
为了检索 TotalMinutes
属性,我在不使用强类型助手的情况下绑定(bind)了属性:
<%=Html.TextBox("Interval", Model.Interval.TotalMinutes)%>
当该字段绑定(bind)回 View Model 类时,它会将数字解析为一天(1440 分钟)。
如何在某些属性上覆盖此行为(最好使用 View 模型本身的属性)?
最佳答案
在这里编写自定义模型绑定(bind)器似乎是个好主意:
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) %>
现在您的 Controller 可以像这样简单:
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);
}
}
关于c# - 来自整数的模型绑定(bind) TimeSpan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4079408/