首页 > 解决方案 > 如何更改 FormData() 的值以接收文本框的值?

问题描述

我正在从 API 获取数据并将其放入表中,到目前为止反应非常好,但是当我尝试从表中的一行编辑数据时。这给了我错误“PUT 400(错误请求)”。我应该如何更改 FormData() 以从“<Form.Control/>”接收值,然后从后端接收它?

---Editar2.js---

handlerSubmit = async (event) => {

        event.preventDefault();
        let formData = new FormData();
        formData.set("", event.target.legenda.value);
        
        let resposta = await fetch("api/FotografiasAPI/" + this.props.idLinha, {
            method: "PUT",
            headers:{'Accept':'application/json','Content-Type':'application/json'},
            body: formData
        });
        if (!resposta.ok) {
        console.error("error:" + resposta.status);
        }
        return await resposta.json();
}
    render(){
        return(
        <Modal
        {...this.props}>
                <Form onSubmit={this.handlerSubmit}>
                    <Form.Group controlId="legenda">
                        <Form.Label>legenda</Form.Label>
                        <Form.Control defaultValue = {this.props.legenda} type="text"name="legenda" required  placeholder="legenda"/>
                    </Form.Group>
                    <Form.Group>
                        <Button variant="primary" type="submit">
                            Editar Restaurante
                        </Button>
                    </Form.Group>
                </Form>    
        </Modal>  
    );}}

---后端---

[HttpPut("{id}")]
public async Task<IActionResult> PutFotografias(int id, [FromForm] Fotografias fotografias)
{
    if (id != fotografias.ID)
    {return BadRequest();}

    _context.Entry(fotografias).State = EntityState.Modified;

    try
    {await _context.SaveChangesAsync();}

    catch (DbUpdateConcurrencyException)
    {
        if (!FotografiasExists(id))
        {return NotFound();}

        else
        {throw;}}

    return NoContent();
}

标签: javascripthtmlasp.netreactjsasp.net-mvc

解决方案


推荐阅读