Html.TextboxFor default value for Integer/Decimal to be Empty instead of 0

后端 未结 8 2286
谎友^
谎友^ 2020-12-08 06:36

I am using the default asp.net MVC 2 syntax to construct TextBox\'s which are integer or decimal for my asp.net MVC web app:

<%: Html.TextBoxFor(model =&g         


        
8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 06:59

    In your model add DisplayFormat attribute

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:#.#}")]  
    decimal  InterestRate { get; set; }
    

    View

    @Html.TextBoxFor(model => model.InterestRate)
    

    This outputs empty instead of 0. More format examples here

    Update

    TextBoxFor does`s not works with format, but EditorFor does:

    @Html.EditorFor(model => model.InterestRate)
    

    Update 2

    It does work for TextBoxFor this way:

    @Html.TextBoxFor(model => model.InterestRate, "{0:#.#}")
    

提交回复
热议问题