【问题标题】:How to perfrom WEBAPI Post call from react Js?如何从 React Js 执行 WEB API Post 调用?
【发布时间】:2018-01-04 11:34:02
【问题描述】:

它已经提出的问题。但我还是没有说清楚。 我必须在 reactjs 中调用 WEBAPI 的 POST 方法。但是我已经在 webapi 中创建了模型。所以我想知道如何将模型数据传递给 reactjs 中的 post call。

型号:

public class EmployeeModels
{
    public int Id { get; set; }
    public string name { get; set; }
    public string mobile { get; set; }
    public string email { get; set; }
    public string dept { get; set; }
    public string erole { get; set; }
}

我的 WEBAPI 发布方法:

   //Insert new Employee
    public IHttpActionResult CreateNewEmployee(EmployeeModels emp)
    {
        using (var ctx = new Employee())
        {
            ctx.tempemp.Add(new tempemp()
            {
                Id = emp.Id,
                name = emp.name,
                mobile = emp.mobile,
                erole = emp.erole,
                dept = emp.dept,
                email = emp.email
            });
            ctx.SaveChanges();
        }
        return Ok();
    }

现在我应该想从 reactjs 发布 Employeemodel。请提出任何建议。

【问题讨论】:

    标签: reactjs asp.net-web-api


    【解决方案1】:

    我已经给出答案了:

    let employee={
        Id:1,
        name:'abc',
        mobile:123456,
        email:'abc@abc.com',
        dept:'IT',
        role:'Developer'
    }
    
    fetch('https://mywebsite.com/CreateNewEmployee/', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(employee)
    })
    .then(function(resp){
        // your response
    })
    

    【讨论】:

    • 太棒了。但我应该想从用户输入中获取数据。没有硬编码。你能举个例子吗?
    • fetch 不是 React 关键字。这是一个 Javascript API。类似于 XHR。 Read Here
    • 看看这个link
    • @PiyushDhamecha 没问题!
    • @Karthikeyan 查看此示例代码:link
    【解决方案2】:

    你可以使用 axios 库。

    npm install axios --save
    

    然后:

    axios.post('/CreateNewEmployee/', {
        Id:1,
        name:'abc',
        mobile:123456,
        email:'abc@abc.com',
        dept:'IT',
        role:'Developer'
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    

    【讨论】:

      猜你喜欢
      • 2016-01-08
      • 2019-11-29
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多