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

React组件向ASP.NET Core MVC控制器提交表单数据的实现方案

实现React组件向.NET Core Web API提交表单数据并插入数据库

后端实现(ProductController)

首先确保项目已配置Entity Framework Core并连接数据库,先创建Product实体类:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

在DbContext中添加对应数据集:

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }

    public DbSet<Product> Products { get; set; }
}

编写ProductController的提交接口,通过依赖注入操作数据库:

[ApiController]
[Route("api/[controller]")]
public class ProductController : ControllerBase
{
    private readonly AppDbContext _dbContext;

    public ProductController(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    [HttpPost]
    public async Task<IActionResult> AddProduct([FromBody] Product product)
    {
        if (ModelState.IsValid)
        {
            _dbContext.Products.Add(product);
            await _dbContext.SaveChangesAsync();
            return Ok(product);
        }
        return BadRequest(ModelState);
    }
}

前端实现(React组件crud.js)

用React原生状态管理+Fetch API处理表单,避免jQuery与虚拟DOM冲突:

import React, { useState } from "react";

function Crud() {
    const [formData, setFormData] = useState({
        name: "",
        price: ""
    });

    const handleInputChange = (e) => {
        const { name, value } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: value
        }));
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        
        try {
            const productData = {
                ...formData,
                price: parseFloat(formData.price)
            };

            const response = await fetch("/api/product", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify(productData)
            });

            if (response.ok) {
                const result = await response.json();
                alert(`产品添加成功,ID:${result.id}`);
                setFormData({ name: "", price: "" });
            } else {
                const error = await response.json();
                alert(`添加失败:${JSON.stringify(error)}`);
            }
        } catch (err) {
            alert(`请求出错:${err.message}`);
        }
    };

    return (
        <form onSubmit={handleSubmit}>
            <input 
                type="text" 
                name="name" 
                placeholder="产品名称" 
                value={formData.name}
                onChange={handleInputChange}
                required
            /> 
            <input 
                type="number" 
                name="price" 
                placeholder="价格" 
                step="0.01"
                value={formData.price}
                onChange={handleInputChange}
                required
            />
            <button type="submit">提交</button>
        </form>
    );
}

export default Crud;

关键注意事项

  • 确保AppDbContext已在Program.cs中注册,示例代码:
    builder.Services.AddDbContext<AppDbContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
    
  • 前端输入框的name属性需与后端Product类的属性名完全匹配
  • 价格字段使用type="number"并设置step="0.01",保证输入合法数值
  • 提交请求时必须将数据序列化为JSON,同时设置请求头Content-Type: application/json
  • 后端接口必须添加[FromBody]特性,才能正确解析JSON格式的请求体

内容的提问来源于stack exchange,提问作者Yugraaj Sandhu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 16:01:27