隐藏日期时间的ASP

隐藏日期时间的ASP

本文介绍了隐藏日期时间的ASP.NET MVC格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,在一个地方被放置在一个隐藏的输入字段一个DateTime属性的模型。

I have a model with a DateTime property that in one place is placed in a hidden input field.

@Html.HiddenFor(m => m.StartDate)

产生下面的HTML:

Which generates the following HTML:

<input id="StartDate" name="StartDate" type="hidden" value="1/1/2011 12:00:00 AM" >

问题是,当时包括在价值和我的自定义日期验证预计##格式/ ## / ####从而导致验证失败的日期。我可以很容易地改变我的自定义日期的验证,使这种情况工作,但这样的隐藏字段放入正确的格式值我宁愿做出来。

The problem is that the time is included in the value and my custom date validation expects a date in the format of ##/##/#### thus causing validation to fail. I can easily alter my custom date validation to make this situation work but I would rather make it so that the hidden field puts the value in the correct format.

我一直在使用该模型属性DisplayFormat属性尝试,但似乎没有改变隐藏输入的格式。

I have tried using the DisplayFormat attribute on the model property but that doesn't seem to change the format of the hidden input.

我也知道我可以手动创建隐藏的输入,并调用StartDate.ToString(MM / DD / YYYY)的价值,但我也是用这个模型中的项目,以便输入都是动态生成的列表索引,有ID喜欢收藏[一些-的Guid] .StartDate这将使它有点困难找出输入ID和名称。

I do realize that I could just create the hidden input manually and call StartDate.ToString("MM/dd/yyyy") for the value but I am also using this model in a dynamically generated list of items so the inputs are indexed and have ids like Collection[Some-Guid].StartDate which would make it a bit more difficult to figure out the id and name of the input.

反正有做'值'值以特定格式出来在页面上呈现的字段作为隐藏输入时?

Is there anyway to make the 'value' value come out in a specific format when rendering the field on the page as a hidden input?

推荐答案

您可以使用自定义编辑模板:

You could use a custom editor template:

public class MyViewModel
{
    [UIHint("MyHiddenDate")]
    public DateTime Date { get; set; }
}

和再定义〜/查看/共享/ EditorTemplates / MyHiddenDate.cshtml

@model DateTime
@Html.Hidden("", Model.ToString("dd/MM/yyyy"))

终于在视图中使用 EditorFor 助手:

@model MyViewModel
@Html.EditorFor(x => x.Date)

这将呈现为日期自定义编辑器模板视图模型的财产,因此使用所需的格式渲染值的隐藏字段。

This will render the custom editor template for the Date property of the view model and consequently render the hidden field with a value using the desired format.

这篇关于隐藏日期时间的ASP.NET MVC格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 02:37