asp.net-mvc – 在使用ASP.Net MVC的Html.TextBoxFor时,如何格式化强大的类型视图中的值

我试图格式化由ASP.Net MVC的TextBoxFor渲染的日期,使用强类型视图的值。日期是可以空的,所以如果它是null我想看到一个空白的值,否则我想看到它的格式为MM / dd / yyyy。
<%= Html.TextBoxFor(model => model.BirthDate,new { style = "width: 75px;" })%>

谢谢,
保罗·斯佩兰萨

解决方法

您可以使用 custom editor template和Html.EditorFor()而不是Html.TextBoxFor()来保持强力打字。

在/ Views / Shared文件夹中创建一个新的EditorTemplates文件夹,并添加一个名为DateTime.ascx的新的MVC 2 View User Control。添加以下内容

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
<%= Html.TextBox("",(Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : string.Empty)) %>

然后在你的看法使用

<%= Html.EditorFor(model => model.BirthDate)%></p>

不要担心“”,命名仍然可以正常工作。

如果您将不同文化格式的DateTime显示认应用程序文化,则需要使用change the culture information或替代创建custom model binder,以便在发回DateTime时使模型绑定工作。

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....