【问题标题】:HTML Textbox showing default value as 0 for int data fieldHTML 文本框将 int 数据字段的默认值显示为 0
【发布时间】:2012-09-20 22:56:24
【问题描述】:

我有一个包含 int 数据字段的文本框。页面加载时,默认显示 0。以下是显示文本框的代码:

<%:Html.TextBoxFor(model => model.Ssn, htmlAttributes: new { @class = "txtBox txtBoxMediumSmall" })%>

model.Ssn 是一个 int
为什么不是空白?应该怎么做才能让它空白?
如果需要更多信息,请告诉我。

【问题讨论】:

  • 你能提供你控制器动作的代码吗?
  • Int 不能为空或 null。它始终默认为 0。
  • 您必须明确应用逻辑。即如果 model.SSn==0 {TextBox.text=""}

标签: c# html asp.net-mvc


【解决方案1】:

你可以这样做

public class MyModel
{
   //Nullable integer
   public int? Ssn {get; set;}  //this should be null by default

   public int SSN {get; set; } //this should be 0 by default

}

【讨论】:

    【解决方案2】:

    由于 bittech poinetd out int 是结构并且没有“空”值 - 0 是默认值,但完全有效的值。

    如果您需要区分“无值”与“默认值”,可以尝试使用int? (Nullable&lt;int&gt;)。

    【讨论】:

      【解决方案3】:

      我会这样做 -

      @Html.TextBoxFor(model => model.Ssn, new { @Value = (@Model.Ssn == 0) ? "" : @Model.Ssn.ToString()})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-31
        • 1970-01-01
        • 2020-07-27
        • 2019-07-11
        相关资源
        最近更新 更多