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

查看:113
本文介绍了如何使用时,格式化的strongy类型视图值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

推荐答案

您可以使用<一个守强类型href=\"http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html\">custom编辑模板和 Html.EditorFor()而不是 Html.TextBoxFor()

创建一个新的 EditorTemplates 的在你的 /浏览文件夹/共享的文件夹并添加一个新的 MVC 2视图用户控件的名为日期时间的.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)) %>

然后在您的视图使用

Then in your view use

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

不要担心,命名仍然能够正常工作。

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

如果您在不同的文化格式的默认应用程序显示文化的日期时间,那么你就需要<一个href=\"http://stackoverflow.com/questions/1417521/asp-net-c-mvc-change-format-for-datetime-directly-on-db-or-model/1417604#1417604\">change文化信息或交替为了创建一个自定义模型粘合剂为模型绑定回发时工作日期时间。

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.

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

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