ReactJS.net部分呈现数据

时间:2017-08-24 19:15:09

标签: reactjs reactjs.net

我在此链接Building Single Page Applications on ASP.NET Core with JavaScriptServices中使用了示例。此示例使用Angular或React等框架构建单页面应用程序(SPA)。一个名为FetchData的现成组件,它从控制器中检索数据,我做了一个像它一样但它部分显示数据。所以请看看照片,看看有什么回应以及为什么html表只显示id列Data partially rendered

// tsx code or reactjs.net - 此文件位于wwwroot -clientapp- component

import * as React from 'react';
import 'isomorphic-fetch';

interface IEmployee {
    firstname: string;
    lastname: string;
    id: number;
    fullname: string;
    enrollmentdate:Date;
}
class SEmployee {
     firstname: string;
    lastname: string;
    id: number;
    fullname: string;
    enrollmentdate: Date;
}
interface IFetchEmployee {
    employees: IEmployee[];
    loading: boolean;
    enableaction:boolean;
}

export class FetchEmployee extends React.Component<{}, IFetchEmployee> {
    constructor() {
        super();
        this.state = { employees: [], loading: false,enableaction:true};
    }

    public render() {
        let contents = this.state.loading
            ? <p><em>Loading...</em></p>
            : FetchEmployee.displayTabularData(this.state.employees);

        return <div>
                   <h1>Employees Page</h1><p>This component demonstrates CRUD operations </p>
                   {FetchEmployee.emptyForm()}
                   <fieldset className="defSetfieldset"><legend>Controls:</legend>
                   <button type="Submitt" id="Sf" onClick={() => { this.readdata() }}>Read Employee</button> |
                   <button type="Submitt" id="Sf"  disabled={this.state.enableaction} onClick={() => { this.savebyinput() }}>Save Employee</button> | 
                   <button type="Submitt" id="df" disabled={this.state.enableaction} onClick={() => { this.delete((document.getElementById("id") as HTMLInputElement).value) }}>Delete Employee</button> | 
                   <button type="Submitt" id="df" disabled={this.state.enableaction} onClick={() => { this.update((document.getElementById("id") as HTMLInputElement).value) }}>Update Employee</button>
                   </fieldset>
                   {contents}
               </div>;
    }
    private static displayTabularData(employees: IEmployee[]) {
        return <table className='table'>
                   <thead>
                   <tr>
                       <th>Id</th>
                       <th>First Name</th>
                       <th>Last Name</th>
                       <th>Full Name</th>
                       <th>Enrollment Date</th>
                   </tr>
                   </thead>
                   <tbody>
                   {employees.map(employee =>
                       <tr key={employee.id}>
                           <td>{employee.id}</td>
                           <td>{employee.firstname}</td>
                           <td>{employee.lastname}</td>
                           <td>{employee.fullname} </td>
                           <td>{employee.enrollmentdate} </td>
                       </tr>
                   )}
                   </tbody>
               </table>;
    }
    private static emptyForm() {
        return <fieldset className="defSetfieldset"><legend>Employee form:</legend>
                   <form className="commentForm">
                       <table className='table'>
                           <tbody>
                           <tr >
                               <td>Id</td>
                               <td><input id="id" type="text" placeholder="id"/> </td>
                           </tr>
                           <tr >
                               <td>First Name</td>
                               <td> <input id="fn" type="text" placeholder="first name"/></td>
                           </tr>
                           <tr>
                               <td>Last Name</td>
                               <td> <input id="ln" type="text" placeholder="last name"/></td>
                           </tr>
                           </tbody>
                       </table>
                   </form></fieldset>;
    }
    private getForm(): SEmployee {
        let id: number = 0;
        id = parseInt((document.getElementById("id") as HTMLInputElement).value);
        let fn = (document.getElementById("fn") as HTMLInputElement).value;
        let ln = (document.getElementById("ln") as HTMLInputElement).value;
        let dt: Date = new Date(2017, 1, 1);

        let emp = new SEmployee();
        emp.id = id;
        emp.firstname = fn;
        emp.lastname = ln;
        emp.enrollmentdate = dt;

        return emp;
    }

    private readdata() {
    fetch('/api/SampleData/GetEmployees')
        .then(response => response.json() as Promise<IEmployee[]>)
        .then(data => {
            this.setState({ employees: data, loading: false, enableaction:true });
        });
    };
    private savebyinput() {
     var datas = {};
        datas = this.getForm();
        var sendto = JSON.stringify(datas);
        fetch('/api/SampleData/AddEmployee?emp=' + sendto,
                {
                    method: "POST",
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json; charset=utf-8'
                    }
                })
            .then(response => response.json() as Promise<IEmployee[]>)
            .then(data => {
                this.setState({ employees: data, loading: false, enableaction: true });
            });
    };
    private delete(Id) {
        var datas = {};
        datas = this.getForm();
        var sendto = JSON.stringify(datas);
        fetch('/api/SampleData/DeleteEmployee?Id=' + sendto,
            {
                method: "POST",
                headers: {
                    'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
                    'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
                }
            })
            .then(response => response.json() as Promise<IEmployee[]>)
            .then(data => {
                this.setState({ employees: data, loading: false, enableaction: true });
            });
    };
    private update(Id) {
        fetch('/api/SampleData/UpdateEmployee?Id=' + Id,
                {
                    method: "POST",
                    headers: {
                        'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
                        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
                    }
                })
            .then(response => response.json() as Promise<IEmployee[]>)
            .then(data => {
                this.setState({ employees: data, loading: false, enableaction: true});
            });
    };
}

//下面的控制器代码

namespace SPA6.Controllers
{
    [Route("api/[controller]")]
    public class SampleDataController : Controller
    {
        private static List<Employee> DataSource = new List<Employee>
        {
            new Employee { FirstName = "Carson",   LastName = "Alexander",
                EnrollmentDate = DateTime.Parse("2010-09-01"), Id =1},
            new Employee { FirstName = "Meredith", LastName = "Alonso",
                EnrollmentDate = DateTime.Parse("2012-09-01") ,Id =2},
            new Employee { FirstName = "Arturo",   LastName = "Anand",
                EnrollmentDate = DateTime.Parse("2013-09-01") ,Id =3},
            new Employee { FirstName = "Gytis",    LastName = "Barzdukas",
                EnrollmentDate = DateTime.Parse("2012-09-01") ,Id =4},
            new Employee { FirstName = "Yan",      LastName = "Li",
                EnrollmentDate = DateTime.Parse("2012-09-01") ,Id =5},
            new Employee { FirstName = "Peggy",    LastName = "Justice",
                EnrollmentDate = DateTime.Parse("2011-09-01") ,Id =6 },
            new Employee { FirstName = "Laura",    LastName = "Norman",
                EnrollmentDate = DateTime.Parse("2013-09-01") ,Id =7},
            new Employee { FirstName = "Nino",     LastName = "Olivetto",
                EnrollmentDate = DateTime.Parse("2005-08-11") ,Id =8}
        };

        [HttpGet("[action]")]
        public IEnumerable<Employee> GetEmployees()
        {
            return DataSource.ToList();
        }

        [HttpPost("[action]")]
        public IEnumerable<Employee> AddEmployee(string emp )
        {
#warning call find or single to check there is no object added with same Id
            // List<Employee>  empobjs = JsonConvert.DeserializeObject<List<Employee>>(emp);
            var empobj = JsonConvert.DeserializeObject<Employee>(emp);
            DataSource.Add(empobj);

            return DataSource;
        }

        [HttpPost("[action]")]
        public IEnumerable<Employee> DeleteEmployee(int Id)
        {
             DataSource.RemoveAll(e=>e.Id == Id);
            return DataSource;

        }

        [HttpPost("[action]")]
        public IEnumerable<Employee> UpdateEmployee(int Id)
        {

            var singleemployee  = DataSource.Single(e=>e.Id == Id);
            singleemployee.FirstName = "Changed To Lamar";
            singleemployee.LastName = "Changed To Gravens";
            return DataSource;

        }

        public class Employee
        {
            public string FirstName { get; set; }
            public int Id { get; set; }
            public DateTime EnrollmentDate { get; set; }
            public string LastName { get; set; }

            public String FullName
            {
                get { return FirstName + "," + LastName; }
            }
        }
    }
}  

0 个答案:

没有答案