2017-11-16 17 views
0

私はReactを初めて使用しています。私は単純な "従業員の詳細"アプリケーションを実装しようとしています。データベースからデータを取得してテーブル形式で表示することができました。しかし、私はフォームからデータベースにデータを投稿できません。あなたがフォームからコントローラにデータを投稿するための詳細なjsxコードを提供できる人がいれば、非常に役に立ちます。また、データをデータベースに保存するためのコントローラー側コード。以下の私のコードを見つけてください。フォームデータをreactjsのASP.NET Web APIコントローラに投稿する方法

これは私のモデル(使用されるエンティティ・フレームワーク)である:

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')) 

フォーム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> 
    ); 
    } 
}); 
+0

フォームデータを送信する必要がありますか? WebApiはJSONを受け入れますので、state.itemを同期させておくと、それをそのままポストすることができます – JamesT

答えて

0

Reactの古くなったバージョンを使用しているようです。あなたのコードにいくつかの問題がありました(私はInputValuesコンポーネントを探していました)。

ラベルが正常に動作するためには、入力時にlabel属性とid属性に一致するhtmlFor属性が必要です。

ボタンをクリックしてフォームを送信すると、ユーザーがキーボードでフォームを送信したときにハンドラがトリガされないため、onSubmitで処理する方が良い理由があります。

私はまた、レフリーは、文字列refは一年以上前に滴下したまったく新しい方法で定義されている現在の1を、一致するようにあなたのリアクト構文を更新し、リンク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> 
    ); 
    } 
}; 

希望します。

関連する問題