You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core中如何正确将Request.Form数据赋值给unit_price字段

正确实现unit_price字段赋值的方案

原代码注释掉直接赋值的原因是:Request.Form["unit_price"]返回的是字符串类型,而unit_price是decimal类型(从代码里的0.01M能看出来),直接赋值会编译报错,必须做类型转换,同时还要考虑前端传入无效值的情况。下面是几种靠谱的实现方式:

方法1:用Decimal.TryParse安全转换(推荐)

这种方式能稳妥处理前端传错值的情况,不会抛出异常,还能自定义默认值:

// 尝试从Form里解析单价,成功就赋值,失败就设默认值
if (decimal.TryParse(Request.Form["unit_price"], out decimal parsedPrice))
{
    productInfo.unit_price = parsedPrice;
}
else
{
    // 解析失败的处理逻辑,比如设0或者记录错误日志
    productInfo.unit_price = 0.00M;
}

方法2:用Convert.ToDecimal(需捕获异常)

如果能确定前端一定会传有效的数字字符串,可以用这个,但要记得处理转换异常:

try
{
    productInfo.unit_price = Convert.ToDecimal(Request.Form["unit_price"]);
}
catch (FormatException)
{
    // 处理格式错误,比如用户输入了非数字内容
    productInfo.unit_price = 0.00M;
}
catch (OverflowException)
{
    // 处理数值太大超出decimal范围的情况
    productInfo.unit_price = decimal.MaxValue;
}

方法3:用ASP.NET Core模型绑定(更优雅)

如果是在Controller里处理请求,推荐用模型绑定自动处理,不用手动从Request.Form取值,代码更简洁:

  1. 先定义对应的模型类:
public class ProductInfo
{
    public string name { get; set; }
    public string category { get; set; }
    public string color { get; set; }
    // 还能加验证规则,比如单价必须大于0
    [Range(0.01, double.MaxValue, ErrorMessage = "单价必须大于0")]
    public decimal unit_price { get; set; }
}
  1. 在Controller的Action里直接接收模型:
[HttpPost]
public IActionResult CreateProduct(ProductInfo productInfo)
{
    if (!ModelState.IsValid)
    {
        // 模型验证失败,返回错误信息
        return BadRequest(ModelState);
    }
    // 后续业务逻辑
    return Ok();
}

ASP.NET Core会自动把Form数据转换成模型对象,还会自动验证数据格式,省心不少。

内容的提问来源于stack exchange,提问作者Viramgama Rinkal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 09:55:04