问题
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.
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/5173021/remove-default-value-for-non-nullable-properties-when-using-editfor-asp-net-mvc