【问题标题】:Display placeholder instead of 0 when binding empty fields of numbers in MVC5在MVC5中绑定数字的空字段时显示占位符而不是0
【发布时间】:2017-08-25 07:14:48
【问题描述】:

我正在编辑 MVC 5API Controllers。当用户按下编辑时,将传递具有从 db 获取的值的模型。但是,当添加新数据时,将使用以下代码传递空模型

var Model = {
    Id: '',
    Type: ''
}
$.ajax({
    url: '@Url.Action("Action", "Control")',
    type: 'POST',
    data: { model: Model },
    success: function (data) {
    }

我的网络控制器

public ActionResult Add(Model model)
{
    return View(model);
}

现在,当我尝试添加值时,string 类型的所有字段都将显示占位符,但 integers 将显示 0 而不是占位符。我知道它是因为我在模型中为数字传递了空字段,但我需要一种解决方法,这样当传递空数字时,它会显示占位符,而不是使用 javascriptjquery 显示 0

【问题讨论】:

  • 你能展示一下你的Model 类的样子吗?如果您想知道是否未设置值,则必须将属性设置为int?/Nullable<int> 而不是int。这允许该值为 null,表示未设置值。
  • 我的Model 格式为public int id {get; set;}。我会试试你的建议
  • 它正在工作,谢谢

标签: javascript jquery asp.net asp.net-web-api


【解决方案1】:

当你想模型绑定避免0默认为整数类型时,请使用可以为空的整数值

 public int? Count { get; set; }

当您从 java 脚本或 jquery 将模型发布为黑色或空时,这将为整数属性分配 null 而不是零。

【讨论】:

    猜你喜欢
    • 2020-02-10
    • 2021-12-14
    • 1970-01-01
    • 2013-04-02
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    相关资源
    最近更新 更多