gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:15:02 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com