代码之家  ›  专栏  ›  技术社区  ›  David Neale

从整数开始的模型绑定时间跨度

  •  6
  • David Neale  · 技术社区  · 14 年前

    TimeSpan 显示 TotalMinutes 属性并绑定回 .

    我已经绑定了属性,而没有使用强类型帮助器来检索 属性:

    <%=Html.TextBox("Interval", Model.Interval.TotalMinutes)%>
    

    当字段被绑定回视图模型类时,它会将数字解析为一天(1440分钟)。

    1 回复  |  直到 14 年前
        1
  •  10
  •   Darin Dimitrov    14 年前

    在这里,编写自定义模型活页夹似乎是一个好主意:

    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);
        }
    }
    
    推荐文章