【发布时间】:2018-06-21 21:15:35
【问题描述】:
几个小时以来,我一直在寻找这个案例的解决方案,但没有找到任何适合我的方法。
这里我们使用逗号作为小数分隔符,当我发送一个像“15,50”这样的值时,在我的控制器中我得到的模型值是“1550”,只有发送“15.50”才有意义”。
我涵盖了以下主题,但没有任何效果。
Set CultureInfo in Asp.net Core to have a . as CurrencyDecimalSeparator instead of ,
Aspnet Core Decimal binding not working on non English Culture
我使用 ajax 发送表单,使用 $form.serializeArray() 如下:
function getFormData(xform) {
var $form = $('#' + xform);
var unindexed_array = $form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function (n, i) {
indexed_array[n['name']] = n['value'];
});
return indexed_array;
}
发送:
function PostFormAjax(controller, metodo, params, redir, divacao, reloadgrid) {
if (params != null) {
var formData = new FormData();
var json = $.parseJSON(JSON.stringify(params));
$(json).each(function (i, val) {
$.each(val, function (k, v) {
console.log(k + " : " + v);
formData.append(k, v);
});
});
}
$.ajax({
url: '/' + controller + '/' + metodo,
data: JSON.stringify(params),
contentType: 'application/json',
type: 'POST',
success: function (data) {
AjaxFim(metodo, data, redir, divacao, reloadgrid);
}
});
}
我的控制器:
[HttpPost]
public IActionResult GravaProduto([FromBody] Produtos produto)
{
if (ModelState.IsValid)
{
//produto.Valorcusto is 1550 and not 15,50 as it was posted
//produto.Valorvenda is 1550 and not 15,50 as it was posted
}
}
我的模型.cs
public partial class Produtos
{
public int Cod { get; set; }
public string Descricao { get; set; }
public decimal Valorcusto { get; set; }
public decimal Valorvenda { get; set; }
}
我尝试在 formData.append(k, v.replace(',', '.')); 中进行替换,但也不起作用,我也不知道哪个字段是小数。
我该怎么办?因为迷路了,本来应该简单的事情变得复杂了。
在找到解决方案之前,我一直在努力:
根据我的地区设置戴口罩:
$('.stValor').mask("#.###.##0,00", { reverse: true });
在发布表单之前,我切换到接受的格式:
$('#fCadAltProd').validator().on('submit', function (e) {
if (e.isDefaultPrevented()) {
} else {
e.preventDefault();
$('.stValor').mask("#,###,##0.00", { reverse: true });
//Ajax post here
}
});
【问题讨论】:
-
只需编写一个自定义模型绑定器,而不是使用文化信息将字符串值解析为小数,请参阅article
-
离题,但你可以pass a
formelement to theFormDataconstructor,它会自动填充你所有的表单元素。 -
如果值为“15,50”,
formData.append(k, v.replace(',', '.'))应该可以工作。如果值为1.150,50,我可以看到它不起作用,因为您还必须用,替换.,也许用v.replace(/[,.]/g, (c) => c == "." ? "," : ".")之类的东西。 -
您可能想查看this answer to How can I parse a string with a comma thousand separator to a number?。您仍然需要确定哪些是数字,但这可以通过像
/^[\d,.]+$/这样的简单正则表达式来完成。
标签: c# asp.net-mvc entity-framework asp.net-core