开发者

Remove default value for non nullable properties when using EditFor [asp.net mvc 3]

How can I remove the default value that is added by default to the textboxes of non nullable properties when开发者_如何学C using the EditFor helper? I don't want that behavior

EDIT

Sorry I didn't give enough information.

For example if you use Html.EditorFor with a property that is DateTime it will set the textbox value to 1/1/0001 automatically. If you use "DateTime?"(nullable), it won't, it just leaves the textbox empty.


You can use UIHint to do it.

Create a file called ShortDate.cshtml in EditorTemplates

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

Decorate your property with the UIHintAttribute referencing our EditorTemplate. Consider my Order class.

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

When you use

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

it should avoid the default value of DateTime

caveat: I just did simple tests, so please take a deep look into it.

hope it helps you


I had to do something like this for my own needs. I used this:

@model DateTime?

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

and it worked pretty nicely for my DateTime values. Ones that didn't have the default value are blank and the ones that have some other DateTime value show the ShortDateString representation of the object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜