c# - 来自整数的模型绑定(bind) TimeSpan

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

我想声明类型为 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/

相关文章:

c# - 在 .NET 中计算电子邮件的大小

c# - 如何在选择另一个@Html.DropDownList 后填充@Html.DropDownList

C# 使用外键填充嵌套类

c# - 从 ASP.NET 插入到 MS Access

asp.net-mvc - Microsoft.jQuery.Unobtrusive.Ajax 与 jQuery 兼容的版本

c# - Asp.Net Mvc 5 图像不显示

c# - 家庭网络上的 SignalR

c# - 跨域不适用于 signalr 2.0

asp.net - 为什么我在 asp.net 中收到数据库连接错误?

c# - 在没有主键的实体中使用表(使用实体代码优先迁移)