FormCollection MVC5没有将十进制传递给控制器

时间:2019-03-22 15:28:31

标签: c# razor asp.net-mvc-5

当我尝试使用<input type="number">从我的视图向我的控制器发布FormCollection时,我总是遇到错误。 feeBackup的数据库类型为decimal(8,2)。我不断收到"Cannot impliticity convert string to decimal?".,然后当我尝试expenseBackup = Int32.Parse(formValues["expenseBackup"])时,我得到"Input string was not in correct format"。我不想在控制器中进行任何转换,我不明白为什么它不会仅仅作为小数通过FormCollection传递。

控制器

 [HttpPost]
        public ActionResult Create(FormCollection formValues)
        {
            var data = new usr_ebillingClientDatabase()
            {
                client = formValues["client"], //is a string from form
                expenseBackup = formValues["expenseBackup"] //is a decimal from form
            };
            dataContext.table1.InsertOnSubmit(data);
            try
            {
                dataContext.SubmitChanges();                    
                return RedirectToAction("Index");
            }
            catch (Exception e)
            {
                return RedirectToAction("Index");
            }           
        }

查看

<div class="form-group">
    <div class="col-md-10">
        @Html.EditorFor(model => model.expenseBackup, new { htmlAttributes = new { @class = "form-control" , , @type="number", @step=".01" } })
    </div>
</div> 

2 个答案:

答案 0 :(得分:1)

当您从formValues["expenseBackup"]读取字段时,它被作为字符串读取。使用Convert.ToDecimal()将其转换为小数。

expenseBackup = Convert.ToDecimal(formValues["expenseBackup"] ?? 0m);

答案 1 :(得分:1)

FormCollection是一个键值对集合(NameValueCollection),它根据提供的键(也是一个字符串)以字符串形式返回值。如果您不确定在提交过程中数字输入采用哪种数字格式,请结合使用decimal.TryParse()和if-condition与string.IsNullOrEmpty()来检查空/空字符串值:

decimal expense;
if (!string.IsNullOrEmpty(formValues["expenseBackup"]) 
    && decimal.TryParse(formValues["expenseBackup"], out expense))
{
    var data = new usr_ebillingClientDatabase()
    {
        client = formValues["client"],
        expenseBackup = expense
    };

    // insert to database
}
else
{
    // unable to parse numeric value, do something else
}

如果您确定在FormCollection中传递的数字表示形式使用默认值以外的某些十进制分隔符,则在与decimal.Parse() / decimal.TryParse()进行解析时,请使用NumberFormatInfo

var numberFormat = new System.Globalization.NumberFormatInfo() { NumberDecimalSeparator = "," };

var data = new usr_ebillingClientDatabase()
{
    client = formValues["client"],
    expenseBackup = decimal.Parse(formValues["expenseBackup"], numberFormat);
};

但是,我建议在FormCollection上使用强类型的viewmodel,因为您使用的是EditorFor,并且当将viewmodel名称作为动作参数包含时,它将直接将属性值传递给控制器​​。