[英]ASP.NET model binding breaks when using decimal values
I have the following scenario. 我有以下情况。 I have a form that post to a controller. 我有一个张贴到控制器的表格。 Everything works fine when I enter a non decimal number on ValorKilometro
input. 当我在ValorKilometro
输入中输入非十进制数字时,一切正常。 I can get the model perfectly on the controller and so. 我可以在控制器上完美地获得模型,等等。 The thing is that when I enter a decimal value the ValorKilometro
property is always set to 0. Why is that?. 问题是,当我输入一个十进制值时, ValorKilometro
属性始终设置为0。为什么? Here is the code: 这是代码:
<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>
Model: 模型:
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; }
}
Controller: 控制器:
[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);
}
I hope someone can help me out with this.Thanks. 我希望有人可以帮助我。谢谢。
Have you tried using @Html.TextBoxFor
helper? 您是否尝试过使用@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" })
You can also add the validation constraint to your model: 您还可以将验证约束添加到模型中:
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; }
}
Note that {0:n2}
indicates 2 decimal places. 注意{0:n2}
表示2个小数位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.