代码之家  ›  专栏  ›  技术社区  ›  NicoRiff

使用十进制值时ASP.NET模型绑定中断

  •  0
  • NicoRiff  · 技术社区  · 6 年前

    我有下面的场景。我有一张寄到管理员的表格。当我在 ValorKilometro 输入。我可以在控制器上得到完美的模型。问题是当我输入一个十进制值时 瓦罗基洛米特 属性始终设置为0。为什么?。代码如下:

    <form name="theForm" action="" style="margin: 0 auto; width: 80%;" method="post" onsubmit="return onFormSubmit();">
        ...
        <div class="form-group">
            <label for="usr">Valor de Kilometro:</label>
            <input type="number" name="ValorKilometro" min="0" step="any" class="form-control" value="@Model.ValorKilometro">
        </div>
        <button type="submit" id="boton" class="btn btn-success">Guardar</button>
    </form>
    

    模型

    public class ConfiguracionModel
    {
        public Guid EmpresaGuid { get; set; }
        public bool MaximoHabilitado { get; set; }
        public int MontoMaximo { get; set; }
        public Guid Moneda { get; set; }
        public Double ValorKilometro { get; set; }
    }
    

    控制器:

        [Authorize, AdminAuthorization]
        [HttpPost]
        public ActionResult Configuracion(ConfiguracionModel configuracion)
        {
            configuracion.EmpresaGuid = SQL.GetEmpresaGuid(User.Identity.Name);
    
            SQL.ModificarConfiguracion(configuracion);
    
            TempData["msg"] = "<script>alert('Los cambios fueron guardados correctamente!.');</script>";
    
            return View(configuracion);
        }
    

    我希望有人能帮我解决这个问题。谢谢。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Hooman Bahreini    6 年前

    你试过用 @Html.TextBoxFor 帮手?

    @model ConfiguracionModel // <-- obviously you need to bind your View to your model
    
    @Html.TextBoxFor(m => m.ValorKilometro, "{0:n2}", new { 
        @class = "form-control", 
        @type = "number", 
        @min = "0" })
    

    还可以将验证约束添加到模型中:

    public class ConfiguracionModel
    {
       public Guid EmpresaGuid { get; set; }
       public bool MaximoHabilitado { get; set; }
       public int MontoMaximo { get; set; }
       public Guid Moneda { get; set; }
    
       [Range(0.0, double.MaxValue)]
       [DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
       public Double ValorKilometro { get; set; }
    }
    

    请注意 {0:n2} 表示两位小数。