c# – 从整数模型绑定TimeSpan

c# – 从整数模型绑定TimeSpan,第1张

概述我想声明我的View Model类型TimeSpan的一些属性来显示TotalMinutes属性并绑定回TimeSpan. 我已经绑定了属性而没有使用强类型帮助器来检索TotalMinutes属性: <%=Html.TextBox("Interval", Model.Interval.TotalMinutes)%> 当该字段绑定回View Model类时,它将该数字解析为一天(1440分钟). 如 我想声明我的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);    }}
总结

以上是内存溢出为你收集整理的c# – 从整数模型绑定TimeSpan全部内容,希望文章能够帮你解决c# – 从整数模型绑定TimeSpan所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1249933.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存