ASP.NET Core - Fetch API不发布数据

ryhaxcpt  于 2023-11-20  发布在  .NET
关注(0)|答案(1)|浏览(107)

我一直在尝试创建一个ASP.NET核心Web应用程序,以将页面上的数据输入发送到我的服务器。我有一个表,其中包含一行,前三列为下拉列表,第四列为复选框。我正在使用HTTPPost的fetch API,但有错误说找不到API/saveData(404)。
下面是我的代码:
CSHTML

<table class="table">
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>Column 3</th>
            <th>Checkbox</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <select class="form-control" id="column1Select">
                    <option>Option 1</option>
                    <option>Option 2</option>
                    <option>Option 3</option>
                </select>
            </td>
            <td>
                <select class="form-control" id="column2Select">
                    <option>Option A</option>
                    <option>Option B</option>
                    <option>Option C</option>
                </select>
            </td>
            <td>
                <select class="form-control" id="column3Select">
                    <option>Choice X</option>
                    <option>Choice Y</option>
                    <option>Choice Z</option>
                </select>
            </td>
            <td>
                <input type="checkbox" id="checkboxInput" />
            </td>
        </tr>
        <!-- You can add more rows here if needed -->
    </tbody>
</table>

<button onclick="postData()">Submit</button>

function postData() {
    var column1Value = document.getElementById("column1Select").value;
    var column2Value = document.getElementById("column2Select").value;
    var column3Value = document.getElementById("column3Select").value;
    var isChecked = document.getElementById("checkboxInput").checked;
    
    var data = {
        column1: column1Value,
        column2: column2Value,
        column3: column3Value,
        isChecked: isChecked
    };

    fetch('api/saveData', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
        .then(response =\> response.json())
        .then(responseData =\> {
            console.log('Success:', responseData);
        })
        .catch(error =\> {
            console.error('Error:', error);
        });
}

字符串
CS

public class splitModel : PageModel {    
    [ApiController]
    [Route("api/[controller]")]
    public class DataController : ControllerBase
    {

        private readonly ApplicationDbContext _context;

        public DataController(ApplicationDbContext context)
        {
            _context = context;
        }

        [HttpPost]
        [Route("SaveData")]
        public async Task<IActionResult> SaveData([FromBody] StockTable data)
        {
            if (data == null)
            {
                return BadRequest("Invalid data received");
            }

            Console.Write(data.Column1);

            var newStockTable = new ApplicationDbContext.StockTable
            {
                Column1 = data.Column1,
                Column2 = data.Column2,
                Column3 = data.Column3, 
                IsChecked = data.IsChecked,
            };

            try
            {
                _context.StockTables.Add(newStockTable);
                await _context.SaveChangesAsync();
                return Ok("Data saved successfully");
            }
            catch (DbUpdateException ex)
            {
                // Log the exception details for troubleshooting
                Console.WriteLine(ex.ToString());
                return BadRequest("Error saving data: " + ex.Message);
            }
        }
        public class StockTable
        {
            public int Id { get; set; } // Assuming this is your primary key column (integer type)
            public string Column1 { get; set; } // Example: string column in your database
            public string Column2 { get; set; } // Another string column
            public string Column3 { get; set; } // Another string column
            public bool IsChecked { get; set; } // Assuming this is a boolean column in your database
        }

        public class StockDataModel
        {
            public string Column1 { get; set; }
            public string Column2 { get; set; }
            public string Column3 { get; set; }
            public bool IsChecked { get; set; }
        }

    }`


我试着把我的数据提取到'https://reqres.in/api/users/23',它的响应如下

Success: {    
"column1": "Option 1",     
"column2": "Option B",     
"column3": "Choice X",     
"isChecked": true,     
"id": "17",     
"createdAt": "2023-10-22T09:30:31.259Z"}

oyt4ldly

oyt4ldly1#

正如Yong Shun所说,你可以使用ApiController类作为根类。
DataController类:

[Route("api/[controller]")]
[ApiController]
public class DataController : ControllerBase
{
    private readonly ApplicationDbContext _context;

    public DataController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpPost]
    [Route("SaveData")]
    public async Task<IActionResult> SaveData([FromBody] StockTable data)
    {...}
}

字符串
在添加路由[Route("api/[controller]")]时,尝试修改uri,如:api/Data/SaveData
如果你删除了[Route("api/[controller]")],只在SaveData操作中使用[Route("SaveData")],你可以使用像SaveData这样的uri。
此外,请确保您在Progarm.cs中为您的API控制器设置了控制器路由,例如:

builder.Services.AddControllers();
app.MapControllers();


然后,在你的头文件中添加'Accept': 'application/json',,比如:

fetch('api/Data/saveData', {
     method: 'POST',
     headers: {
         'Accept': 'application/json',
         'Content-Type': 'application/json'
     },
     body: JSON.stringify(data)
 })
     .then(response => response.json())
     .then(responseData => {
         console.log('Success:', responseData);
     })
     .catch(error => {
         console.error('Error:', error);
     });


headers-指定Accept和Content-Type HTTP请求头。这两个头都设置为application/json,以分别指定接收和发送的媒体类型。
结果:x1c 0d1x
您可以查看Tutorial: Call an ASP.NET Core web API with JavaScriptTutorial: Create a web API with ASP.NET Core以了解更多信息。

相关问题