How to set a default value with Html.TextBoxFor?

后端 未结 12 2137
清歌不尽
清歌不尽 2020-12-04 07:24

Simple question, if you use the Html Helper from ASP.NET MVC Framework 1 it is easy to set a default value on a textbox because there is an overload Html.TextBox(strin

相关标签:
12条回答
  • 2020-12-04 07:49

    you can try this

    <%= Html.TextBoxFor(x => x.Age, new { @Value = "0"}) %>
    
    0 讨论(0)
  • 2020-12-04 07:50

    Using @Value is a hack, because it outputs two attributes, e.g.:

    <input type="..." Value="foo" value=""/>
    

    You should do this instead:

    @Html.TextBox(Html.NameFor(p => p.FirstName).ToString(), "foo")
    
    0 讨论(0)
  • 2020-12-04 07:51

    You can simply do :

    <%= Html.TextBoxFor(x => x.Age, new { @Value = "0"}) %>
    

    or better, this will switch to default value '0' if the model is null, for example if you have the same view for both editing and creating :

    @Html.TextBoxFor(x => x.Age, new { @Value = (Model==null) ? "0" : Model.Age.ToString() })
    
    0 讨论(0)
  • 2020-12-04 07:51

    This work for me

    @Html.TextBoxFor(model => model.Age, htmlAttributes: new { @Value = "" })
    
    0 讨论(0)
  • 2020-12-04 08:00

    Here's how I solved it. This works if you also use this for editing.

    @Html.TextBoxFor(m => m.Age, new { Value = Model.Age.ToString() ?? "0" })
    
    0 讨论(0)
  • 2020-12-04 08:04

    If you have a partial page form for both editing and adding, then the trick I use to default value to 0 is to do the following:

    @Html.TextBox("Age", Model.Age ?? 0)
    

    That way it will be 0 if unset or the actual age if it exists.

    0 讨论(0)
提交回复
热议问题