javascript - 如何使用react发送表单数据

标签 javascript reactjs asp.net-web-api asp.net-web-api2

我有一个使用此方法的 webapi:

 public async Task<IHttpActionResult>  PutTenant(string id, Tenant tenant, HttpPostedFile certificateFile)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["AzureStorageKey"].ToString());
            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference(ConfigurationManager.AppSettings["certificatesContainer"].ToString());

            // Retrieve reference to a blob named "myblob".
            CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");

            // Create or overwrite the "myblob" blob with contents from a local file.
            blockBlob.Properties.ContentType = certificateFile.ContentType;
            blockBlob.UploadFromStream(certificateFile.InputStream);

            var tenantStore = CosmosStoreFactory.CreateForEntity<Tenant>();
            tenant.CertificatePath = blockBlob.Uri;

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            if (id != tenant.TenantId)
            {
                return BadRequest();
            }

            var added = await tenantStore.AddAsync(tenant);
            return StatusCode(HttpStatusCode.NoContent); 
        }

现在我有一个 react 表单:

import React, { Component } from 'react';

import { Row, Col } from 'antd';
import PageHeader from '../../components/utility/pageHeader';
import Box from '../../components/utility/box';
import LayoutWrapper from '../../components/utility/layoutWrapper.js';
import ContentHolder from '../../components/utility/contentHolder';
import basicStyle from '../../settings/basicStyle';
import IntlMessages from '../../components/utility/intlMessages';
import { adalApiFetch } from '../../adalConfig';
import axios from 'axios';
const API_SERVER = "example.azure.com/upload";

export default class extends Component {
  constructor(props) {
    super(props);

  }

  upload(e) {

    let data = new FormData();

    //Append files to form data
    let files = e.target.files;
    for (let i = 0; i < files.length; i++) {
      data.append('files', files[i], files[i].name);
    }

    let d = {
      method: 'post',
      url: API_SERVER,
      data: data,
      config: {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
      },
      onUploadProgress: (eve) => {
        let progress = utility.UploadProgress(eve);
        if (progress == 100) {
          console.log("Done");
        } else {
          console.log("Uploading...",progress);
        }
      },
    };
    let req = axios(d);

     return new Promise((resolve)=>{
        req.then((res)=>{
            return resolve(res.data);
        });
    });

  }


  render(){
    const { data } = this.state;
    const { rowStyle, colStyle, gutter } = basicStyle;


    return (
      <div>
        <LayoutWrapper>
        <PageHeader>{<IntlMessages id="pageTitles.TenantAdministration" />}</PageHeader>
        <Row style={rowStyle} gutter={gutter} justify="start">
          <Col md={12} sm={12} xs={24} style={colStyle}>
            <Box
              title={<IntlMessages id="pageTitles.TenantAdministration" />}
              subtitle={<IntlMessages id="pageTitles.TenantAdministration" />}
            >
              <ContentHolder>
              {//Put Form here with file upload.
              }
              <form>
              Name:     <input type="text" name="tenanturl" />
              Password: <input type="text" name="password" />

              <input onChange = { e => this.upload(e) } type = "file" id = "files" ref = { file => this.fileUpload } />
              <input type="submit" value="Submit" />
              </form>
              </ContentHolder>
            </Box>
          </Col>
        </Row>
      </LayoutWrapper>
      </div>
    );
  }
}

租户对象有 2 个字符串属性,它们的形式相同。 如何将这 2 个字符串属性作为租户对象发送?如何触发提交表单?

顺便说一下,R​​eact 中的表单新手

最佳答案

这是我的样本。基本上我将定义要发送到 API 的属性。在本例中我使用 axios

const data = {
    Username: this.state.username,
    Email: this.state.email,
}

axios
      .post(url, data)
      .then(data => {
        //something
      })
      .catch(error => {
        //something
      });

在我的 API Controller 中,我将使用 [FormBody] 标签接收传递到服务器的数据

public async Task<IActionResult> AddNewUser([FromBody] UserInputViewModel userInputVm)

请根据您的代码进行相应调整。如果您有任何问题,请告诉我。

关于javascript - 如何使用react发送表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51346619/

相关文章:

javascript - 特定的 javascript 代码仅适用于警报语句

javascript - 附加到通过 Angularjs 中的输入文本添加的新 span 元素的数组

javascript - jQuery : pass argument to ajax error function

javascript - react : import local files from a dynamic location

javascript - 如何在模态之外使用 handleClick 关闭模态?

c# - ConfigureAwait(false) 维护线程身份验证,但默认情况下它不会

javascript - 谷歌地图 api 无法加载 ajax 请求

javascript - react 映射返回的对象错误作为 react 子项无效

java - 将 http post 发送到 dot net webapi

c# - 升级到MVC 5和Web API 2后,如何使我的Web API应用再次运行?