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

3k views Asked by At

How can I remove the default value that is added by default to the textboxes of non nullable properties when 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.

2

There are 2 answers

0
Kim Tranjan On

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

0
itsmatt On

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.