2017-11-16 4 views
0

저는 React를 처음 접했습니다. 간단한 "직원 세부 정보"를 구현하려고했습니다. 데이터베이스에서 데이터를 가져 와서 테이블 형식으로 표시 할 수있었습니다. 그러나 양식에서 데이터베이스로 데이터를 게시 할 수 없습니다. 어떤 사람이 형식에서 컨트롤러로 데이터를 게시 할 수있는 상세한 jsx 코드를 제공 할 수 있다면 매우 유용 할 것입니다. 또한 데이터를 데이터베이스에 저장하는 컨트롤러 측 코드. 아래 코드를 찾으십시오.양식 데이터를 reactjs의 ASP.NET 웹 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으로 처리하는 것이 더 나은 이유가 처리기를 트리거하지 않습니다.

또한 심판이 문자열 심판 년 이상 전에 떨어졌다 완전히 새로운 방식으로 정의 된 현재, 링크 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> 
    ); 
    } 
}; 

희망 하시겠습니까?