asp.net-mvc 日期时间字段和 Html.TextBoxFor() 助手。如何正确使用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3734829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:30:16  来源:igfitidea点击:

DateTime field and Html.TextBoxFor() helper. How to use it correctly?

asp.net-mvchtml-helper

提问by Lorenzo

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

我的模型中有一个 DateTime 字段。如果我尝试以这种方式在强类型部分视图中使用此字段

<%= 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.

无论如何,如果我使用它删除格式ToString("dd/MM/yyyy"),一切正常,但该字段使用我根本不需要的时间部分进行格式化。

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; }

采纳答案by Rohrbs

Create an editor template called DateTime.ascx

创建一个名为 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:

把它放在你的 Views/Shared/EditorTemplates 文件夹中。现在当你打电话时:

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

Your DateTime will be formatted without the time.

您的 DateTime 将在没有时间的情况下进行格式化。

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

这将发生在所有以这种方式调用的 DateTimes 中,但是......

Custom html attributes can be used in this way:

自定义 html 属性可以这样使用:

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

It passes through to the EditorTemplate as ViewData.

它作为 ViewData 传递到 EditorTemplate。

回答by DarkMFJ

i use this in mvc 4. it also works~

我在 mvc 4 中使用它。它也有效~

@Html.TextBoxFor(x => x.DatePurchase, "{0:yyyy-MM-dd}", new { @class = "dateInput", @placeholder = "plz input date" })

回答by Darin Dimitrov

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

And in your model:

在你的模型中:

[DisplayFormat(ApplyFormatInEditMode = true, 
               DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime DataUdienza { get; set; }


The drawback with EditorFor is that you cannot apply custom html attributes to the generated field. As an alternative you could use the TextBoxhelper:

EditorFor 的缺点是您不能将自定义 html 属性应用于生成的字段。作为替代方案,您可以使用TextBox助手:

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

回答by Bondolin

At least if using razor, you can name the template, so you don't need to use the same template for all DateTimes:

至少如果使用剃刀,您可以命名模板,因此您不需要为所有日期时间使用相同的模板:

@Html.EditorFor(m => m.StartDate, "Date")

where Date.cshtml contains a TextBoxFor or some other editor, like @JungleFreak had explained:

其中 Date.cshtml 包含一个 TextBoxFor 或其他一些编辑器,就像 @JungleFreak 解释的那样:

@model DateTime?

@Html.TextBox("", Model.HasValue ? Model.Value.ToShortDateString() : string.Empty, 
    new { data_datepicker = true })

回答by bussa

Perhaps an extension method could be created:

也许可以创建一个扩展方法:

    public static MvcHtmlString DateTimeFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
    {
        var compilationResult = expression.Compile();
        TValue dateValue = compilationResult((TModel)html.ViewDataContainer.ViewData.Model);
        var body = (MemberExpression)expression.Body;
        return html.TextBox(body.Member.Name, (Convert.ToDateTime(dateValue)).ToCustomDateFormat(), new { id = body.Member.Name, datepicker = true });
    }

the method ToCustomDateFormat could be an extension method for dateTime types which returns string value in desired format.

ToCustomDateFormat 方法可以是 dateTime 类型的扩展方法,它以所需格式返回字符串值。

Usage:

用法:

@Html.DateTimeFor(x=>x.AnyDateTimeProperty)

Worked fine for me (for DateTimeand DateTime?properties), although I am not sure if compiling the expression on run-time is a good idea.

对我来说效果很好(对于DateTimeDateTime?属性),尽管我不确定在运行时编译表达式是否是一个好主意。