【问题标题】:How to post form data to ASP.NET web api controller in reactjs如何在 reactjs 中将表单数据发布到 ASP.NET Web api 控制器
【发布时间】:2017-11-16 07:12:31
【问题描述】:

我是 React 新手,我一直在尝试实现一个简单的“员工详细信息”crud 应用程序。我能够从数据库中获取数据并以表格格式显示。但我无法将数据从表单发布到数据库。如果有人可以为我提供详细的 jsx 代码以将数据从表单发布到控制器,那将非常有帮助。以及将数据保存到数据库的控制器端代码。请在下面找到我的代码。

这是我的模型(使用的实体框架):

public partial class EmployeeTable
    {
        public int EmployeeID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
        public string Designation { get; set; }
        public long Salary { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
    }

控制器:

namespace ReactModelApp.Controllers
{
    [RoutePrefix("api/Employee")]
    public class EmployeeController : ApiController
    {
        EmployeeEntities db = new EmployeeEntities();

        [Route("GetEmployeeList")]
        public IQueryable<EmployeeTable> GetEmployeeList()
        {
            return db.EmployeeTables.AsQueryable();
        }

        [Route("InputEmployee")]

        public HttpResponseMessage InputEmployee([FromBody]EmployeeTable Employee)
        {
            try
            {
                using (EmployeeEntities entities = new EmployeeEntities())
                {
                    entities.EmployeeTables.Add(Employee);
                    entities.SaveChanges();
                    var message = Request.CreateResponse(HttpStatusCode.Created, Employee);
                    message.Headers.Location = new Uri(Request.RequestUri + Employee.EmployeeID.ToString());
                    return message;
                }
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
    }
}

用于显示数据库数据的 React.jsx 代码:

var EmployeeRow = React.createClass({

      render: function () {
          return(
              <tr>
                  <td>{this.props.item.EmployeeID}</td>
                  <td>{this.props.item.FirstName}</td>
                  <td>{this.props.item.LastName}</td>
                  <td>{this.props.item.Gender}</td>
                  <td>{this.props.item.Designation}</td>
                  <td>{this.props.item.Salary}</td>
                  <td>{this.props.item.City}</td>
                  <td>{this.props.item.Country}</td>
              </tr>

              );
      }
  });

  var EmployeeTable = React.createClass({

      getInitialState: function(){

          return{
              result:[]
          }
      },
      componentWillMount: function(){

          var xhr = new XMLHttpRequest();
          xhr.open('get', this.props.url, true);
          xhr.onload = function () {
              var response = JSON.parse(xhr.responseText);

              this.setState({ result: response });

          }.bind(this);
          xhr.send();
      },
      render: function(){
          var rows = [];
          this.state.result.forEach(function (item) {
              rows.push(<EmployeeRow key={item.EmployeeID} item={item} />);
      });
  return (<table className="table">
     <thead>
         <tr>
            <th>EmployeeID</th>
            <th>FirstName</th>
            <th>LastName</th>
            <th>Gender</th>
            <th>Designation</th>
            <th>Salary</th>
            <th>City</th>
            <th>Country</th>
         </tr>
     </thead>

      <tbody>
          {rows}
      </tbody>

  </table>);
  }

  });

  ReactDOM.render(<EmployeeTable url="api/Employee/GetEmployeeList" />,
          document.getElementById('grid')) 

Form React jsx 代码:

var InputValues=React.createClass({
  handleClick:function(){


},

  render:function(){
    return(
      <div>       
          <form>
          <label id="firstname">First Name </label><br/>
          <input type="text"  placeholder="Enter First Name" ref="firstName"   />
          <br/><br/><label id="lastname">Last Name: </label><br/>
          <input type="text"  placeholder="Enter Last Name"  ref="lastName"   />
          <br/><br/><label id="gender">Gender: </label><br/>
          <input type="text"  placeholder="Gender"  ref="gender"   />
          <br/><br/><label id="designation">Designation: </label><br/>
          <input type="text"  placeholder="Enter Designation"  ref="designation"   />
          <br/><br/><label id="salary">Salary: </label><br/>
          <input type="number"  placeholder="Enter Salary"  ref="salary"   />
          <br/><br/><label id="city">City: </label><br/>
          <input type="text"  placeholder="Enter City"  ref="city"   />
          <br/><br/><label id="country">Country: </label><br/>
          <input type="text"  placeholder="Enter Country"  ref="country"   />
          <p>
            <button type="button" onClick={this.handleClick}>Submit</button>
          </p>
        </form>
      </div>
    );
  }
});

【问题讨论】:

  • 您是否有理由需要发布表单数据? WebApi 将接受 JSON,因此如果您保持 state.item 同步,您可以将其直接发布到它

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


【解决方案1】:

看来您使用的是非常过时的 React 版本。您的代码中有几个问题(我只是在查看 InputValues 组件)。

为了使标签按预期工作,您需要在标签上具有匹配的 htmlFor 属性,在输入上具有匹配的 id 属性。

当用户使用键盘提交表单时,通过单击按钮处理表单提交不会触发处理程序,这就是为什么最好使用 onSubmit 处理它。

我还更新了您的 React 语法以匹配当前语法,其中 refs 以全新的方式定义,其中字符串 ref 在一年前被删除,更多详细信息链接 https://reactjs.org/docs/refs-and-the-dom.html

我想你正在学习一个教程,但敦促你找到一个具有更新语法的教程,因为你以后将很难调整。

无论如何,这里的代码将调用您的后端服务并为其提供表单数据。

class InputValues extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    const data = new FormData();
    data.append('firstName', this.firstName.value);
    data.append('lastname', this.lastname.value);
    data.append('gender', this.gender.value);
    data.append('designation', this.designation.value);
    data.append('salary', this.salary.value);
    data.append('city', this.city.value);
    data.append('country', this.country.value);
    var xhr = new XMLHttpRequest();
    xhr.open('post', this.props.url, true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function() {
      if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
        // Do something on success
      }
    }
    xhr.send(data);
  }

  render() {
    return(
      <div>       
          <form onSubmit={this.handleSubmit}>
          <label htmlFor="firstname">First Name </label><br/>
          <input id="firstname" type="text"  placeholder="Enter First Name" ref={(firstName) => this.firstName = firstName} />
          <br/><br/>
          <label htmlFor="lastname">Last Name: </label><br/>
          <input id="lastname" type="text"  placeholder="Enter Last Name"  ref={(lastname) => this.lastname = lastname} />
          <br/><br/>
          <label htmlFor="gender">Gender: </label><br/>
          <input id="gender" type="text"  placeholder="Gender"  ref={(gender) => this.gender = gender} />
          <br/><br/>
          <label htmlFor="designation">Designation: </label><br/>
          <input id="designation" type="text"  placeholder="Enter Designation" ref={(designation) => this.designation = designation} />
          <br/><br/>
          <label htmlFor="salary">Salary: </label><br/>
          <input id="salary" type="number"  placeholder="Enter Salary" ref={(salary) => this.salary = salary} />
          <br/><br/>
          <label htmlFor="city">City: </label><br/>
          <input id="city" type="text"  placeholder="Enter City" ref={(city) => this.city = city} />
          <br/><br/>
          <label htmlFor="country">Country: </label><br/>
          <input id="country" type="text"  placeholder="Enter Country" ref={(country) => this.country = country} />
          <p>
            <button type="submit">Submit</button>
          </p>
        </form>
      </div>
    );
  }
};

希望有帮助!

【讨论】:

    猜你喜欢
    • 2014-01-27
    • 2018-04-30
    • 2021-01-19
    • 2016-07-12
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    相关资源
    最近更新 更多