使用 ASP.Net MVC 的 Html.TextBoxFor 时如何在强类型视图中格式化值 [英] How to format the value in a strongy typed view when using ASP.Net MVC's Html.TextBoxFor

查看:18
本文介绍了使用 ASP.Net MVC 的 Html.TextBoxFor 时如何在强类型视图中格式化值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用强类型视图的值来格式化由 ASP.Net MVC 的 TextBoxFor 呈现的日期.日期可以为空,所以如果它为空,我希望看到一个空白值,否则我希望以 MM/dd/yyyy 格式查看它.

I am trying to format a date rendered by ASP.Net MVC's TextBoxFor using the value of a strongly typed view. The date is nullable so if it is null I want to see a blank value, otherwise I want to see it in the format MM/dd/yyyy.

<%= Html.TextBoxFor(model => model.BirthDate, new { style = "width: 75px;" })%>

谢谢,
保罗·斯佩兰萨

Thanks,
Paul Speranza

推荐答案

您可以使用 自定义编辑器模板Html.EditorFor() 而不是 Html.TextBoxFor().

You can keep the strong typing by using a custom editor template and Html.EditorFor() instead of Html.TextBoxFor().

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

Create a new EditorTemplates folder in your /Views/Shared folder and add a new MVC 2 View User Control named DateTime.ascx. Add the following

<%@ 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>

不用担心",命名仍然可以正常工作.

Don't worry about the "", the naming will still work correctly.

如果您以与默认应用程序文化不同的文化格式显示 DateTime,则需要 更改文化信息 或者创建一个 自定义模型绑定器,以便模型绑定在回发 DateTime 时起作用.

If you are displaying the DateTime in a different culture format to the default application culture then you will need to change the culture information or alternatively create a custom model binder in order for the model binding to work when posting back the DateTime.

这篇关于使用 ASP.Net MVC 的 Html.TextBoxFor 时如何在强类型视图中格式化值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆