加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 在使用ASP.Net MVC的Html.TextBoxFor时,如何格式

发布时间:2020-12-16 00:36:45 所属栏目:asp.Net 来源:网络整理
导读:我试图格式化由ASP.Net MVC的TextBoxFor渲染的日期,使用强类型视图的值。日期是可以空的,所以如果它是null我想看到一个空白的值,否则我想看到它的格式为MM / dd / yyyy。 %= Html.TextBoxFor(model = model.BirthDate,new { style = "width: 75px;" })%
我试图格式化由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时使模型绑定工作。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读