使用EditFor当除去用于非空的属性默认值[asp.net MVC 3](Remove defau

2019-09-27 05:42发布

我怎样才能删除默认情况下使用EditFor助手当添加到非空的属性的文本框的默认值? 我不希望这样的行为

编辑

对不起,我没有提供足够的信息。

例如,如果您使用Html.EditorFor与DateTime的是它会自动将文本框的值设置为1/1/0001的属性。 如果使用“日期时间?”(可为空),它不会,它只是离开文本框为空。

Answer 1:

您可以使用UIHint做到这一点。

中创建一个名为EditorTemplates文件ShortDate.cshtml

@model DateTime
@{ var value = Model == default(DateTime) ? null : Model.ToShortDateString(); }
@Html.TextBox(string.Empty, value)

装饰与UIHintAttribute参考我们的EditorTemplate你的财产。 考虑我的Order类。

public class Order {
    [UIHint("ShortDate")]
    public DateTime Date { get; set; }
}

当您使用

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

应避免的DateTime的默认值

警告:我只是简单的测试,所以请大家深入探讨它。

希望它可以帮助你



Answer 2:

我不得不做这样的事情对于我自己的需要。 我用这个:

@model DateTime?

@Html.TextBox("", (Model.Value != default(DateTime) ? Model.Value.ToShortDateString() : string.Empty))

和它的工作非常好听我的DateTime值。 这并没有默认值的有空白,并有一些其他的日期时间值的那些表现出物体的ShortDateString表示。



文章来源: Remove default value for non nullable properties when using EditFor [asp.net mvc 3]