【问题标题】:Model binding TimeSpan from integer来自整数的模型绑定 TimeSpan
【发布时间】:2010-11-03 00:10:48
【问题描述】:

我想声明 TimeSpan 类型的视图模型的一些属性以显示 TotalMinutes 属性并绑定回 TimeSpan

为了检索TotalMinutes 属性,我在不使用强类型帮助器的情况下绑定了属性:

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

当该字段绑定回 View Model 类时,它会将数字解析为一天(1440 分钟)。

如何在某些属性上覆盖此行为(最好使用视图模型本身的属性)?

【问题讨论】:

    标签: c# asp.net asp.net-mvc


    【解决方案1】:

    在这里编写自定义模型绑定器似乎是个好主意:

    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);
        }
    }
    

    【讨论】:

    • 完美运行。它没有点击可以通过使用像这样的值提供程序绑定到TimeSpan 的属性。谢谢。
    猜你喜欢
    • 2013-04-28
    • 2017-03-06
    • 2014-09-10
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    相关资源
    最近更新 更多