DateTime字段和Html.TextBoxFor()辅助。如何正确使用它呢? [英] DateTime field and Html.TextBoxFor() helper. How to use it correctly?

查看:516
本文介绍了DateTime字段和Html.TextBoxFor()辅助。如何正确使用它呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的模型中DateTime字段。如果我尝试这种方式使用一个强类型的局部视图这一领域

 <%= Html.TextBoxFor(型号=> model.DataUdienza.ToString(DD / MM / YYYY),新{风格=宽度:120像素}) %GT;

我会得到以下编译运行时错误

  System.InvalidOperationException:模板只能与现场访问,访问属性,一维数组的索引,或单参数自定义索引前pressions使用。

无论如何,如果我用它去除的格式,的ToString(DD / MM / YYYY)后,一切正常,但现场使用,我不需要在所有的时间部分格式化。

我哪里做错了吗?这是处理这个正确的方式?

感谢您的帮助!

修改

这是在模型类财产申报

  [必需]
[DisplayName的(数据Udienza)]
[数据类型(DataType.Date)
[DisplayFormat(ApplyFormatInEditMode = TRUE,DataFormatString ={0:DD / MM / YYYY})]
公众的DateTime DataUdienza {搞定;组; }


解决方案

创建一个名为DateTime.ascx编辑模板

 <%@控制语言=C#继承=System.Web.Mvc.ViewUserControl<&System.DateTime的GT;? %GT;
<%= Html.TextBox(?(Model.HasValue Model.Value.ToString(MM / DD / YYYY)的String.Empty),ViewData的)%GT;

把它放在你查看/共享/ EditorTemplates文件夹中。现在,当你调用:

 <%= Html.EditorFor(型号=> model.DataUdienza)%GT;

您的DateTime将没有时间进行格式化。

这将与所谓的这种方式都发生DateTime对象,不过......

定制HTML属性可以以这种方式被使用:

 <%= Html.EditorFor(型号=> model.DataUdienza,新{customAttr =定制,@class =类})%GT;

它贯穿于EditorTemplate作为ViewData的。

I have a DateTime field in my Model. If I try to use this field in a strong typed partial view this way

<%= Html.TextBoxFor(model => model.DataUdienza.ToString("dd/MM/yyyy"), new { style = "width: 120px" })  %>

I will get the following compilation error at runtime

System.InvalidOperationException : Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

Anyway if I use it removing the formatting, ToString("dd/MM/yyyy"), everything works but the field is formatted using the time part which I dont need at all.

Where I am doing wrong? Which is the correct way to handle this?

thanks for helping!

EDIT

This is the property declaration in the model class

[Required]
[DisplayName("Data Udienza")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DataUdienza { get; set; }

解决方案

Create an editor template called DateTime.ascx

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

Put it in your Views/Shared/EditorTemplates folder. Now when you call:

<%= Html.EditorFor(model => model.DataUdienza) %>

Your DateTime will be formatted without the time.

This will happen with all DateTimes called this way, though...

Custom html attributes can be used in this way:

<%= Html.EditorFor(model => model.DataUdienza, new {customAttr = "custom", @class = "class"}) %>

It passes through to the EditorTemplate as ViewData.

这篇关于DateTime字段和Html.TextBoxFor()辅助。如何正确使用它呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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