0

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

// tsx 代码或 reactjs.net - 这个文件在 wwwroot -clientapp- 组件中找到

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; }
            }
        }
    }
}  
4

0 回答 0