c# – 从整数模型绑定TimeSpan

我想声明我的View Model类型TimeSpan的一些属性显示TotalMinutes属性并绑定回TimeSpan.

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

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

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

如何在某些属性上覆盖此行为(最好使用View Model本身的属性)?

解决方法

编写自定义模型绑定器似乎是一个好主意:
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);
    }
}

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...