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

时间:2018-10-29 22:44:43

标签: c# asp.net-mvc model-binding

我有以下情况。我有一个张贴到控制器的表格。当我在ValorKilometro输入中输入非十进制数字时,一切正常。我可以在控制器上完美地获得模型,等等。问题是,当我输入一个十进制值时,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 个答案:

答案 0 :(得分:0)

您是否尝试过使用 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main3); db = .... // initialize your db; data = {Objects.requireNonNull(db).viewdata3()}; .... } 助手?

@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; } } 表示小数点后两位。