ASP. NET Core API и React JS - PullRequest
       130

ASP. NET Core API и React JS

1 голос
/ 15 марта 2020

Я создал ASP. NET Базовый пример API и React CURD. Я слежу за этим примером , но для просмотра я использовал реакции semanti c ui. Я новичок, чтобы реагировать и ASP. NET на любое предложение, чтобы я мог улучшить свой код.

Я могу получить, POST, PUT и DELETE запись клиента, но есть некоторые небольшие проблемы или замечания что я не знаю, как реализовать. Они следующие:

1 - я использовал модал, поэтому я могу открыть форму как всплывающее окно (AddCustomer - форма для добавления и редактирования записи), так как у меня есть две функции, чтобы ОТКРЫТЬ и ЗАКРЫТЬ модал, но я не как вызвать их у Клиента. js, а также при успешном выполнении запроса POST, PUT, DELETE.

2 - Когда я открываю FORM для записи ADD или EDIT, я не могу сохранить ее в состоянии. Когда я пытаюсь ввести в поле ввода, оно не сохраняется в имени и адресе.

3 - Также вы можете видеть в клиенте. js Я скрываю форму и удаляю модальные, но я хочу закрыть их на Выполнение задач POST, PUT и DELETE.

Это Customer. js

import React from 'react';

import AddCustomer from './AddCustomer';
import CustomerView from './CustomerView';
import DeleteRecord from './DeleteRecord';

export default class Customer extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        isAddCustomer:false,
        isEditCustomer:false,
        isDeleteCustomer:false,
        closeForm:false,
        singleCustomer:{},
        deleteId:{}
    }

}

onCreate = () => {
    console.log("is add customer true ")
    this.setState({isAddCustomer:true})
}

onFormControl = () =>{
    this.setState({
        isAddCustomer:false,
        isEditCustomer:false
    })
}

onDeleteClick = customerId => {
    const headerTitle = "Customer";
    console.log("onDeleteClick")
    this.setState({
        isDeleteCustomer:true,
        deleteId:{
            ID:customerId,
            title:headerTitle,
            open:true
        }
    });
}

//New Customer record
onAddFormSubmit = data => {

    console.log("In add form submit")
    console.log(data)

    let customerApi = 'https://localhost:44387/api/Customers';
    let method = '';

    if(this.state.isEditCustomer){
        console.log("In Edit api")
        console.log(this.state.editCustomerId)
        customerApi = 'https://localhost:44387/api/Customers/' + this.state.editCustomerId;
        method = 'PUT'

    }else{
        console.log("In Add api")
        customerApi = 'https://localhost:44387/api/Customers';
        method = 'POST'

    }

    const myHeader = new Headers({
        'Accept':'application/json',
            'Content-type':'application/json'
    });

    fetch(customerApi,{
        method:method,
        headers:myHeader,
        body:JSON.stringify(data)

    })
    .then(res => res.json())
    .then(
        (result) => {
            this.setState({
                users:result,
                isAddCustomer:false,
                isEditCustomer:false
            })
        },(error) => {
            this.setState({ error });
        }
    )
}

//Edit customer record
onEditCustomer = customerId => {

    //Get ID, name and address
    this.setState({
        editCustomerId:customerId
    });

    const customerApi = 'https://localhost:44387/api/Customers/'+customerId;

    const myHeader = new Headers({
        'Accept':'application/json',
            'Content-type':'application/json; charset=utf-8'
    });

    fetch(customerApi,{
        method:'GET',
        headers:myHeader

    })
    .then(res => res.json())
    .then(
        (result) => {
            this.setState({
                isEditCustomer:true,
                isAddCustomer:false,
                singleCustomer:{
                    customer:result,
                    isEditCustomer:true
                }
            })
        },(error) => {
            this.setState({ error });
        }
    )

}

//Delete Customer

onDeleteCustomer = customerId => {

    const customerApi = 'https://localhost:44387/api/Customers/'+customerId;

    const myHeader = new Headers({
        'Accept':'application/json',
            'Content-type':'application/json; charset=utf-8'
    });

    fetch(customerApi,{
        method:'DELETE',
        headers:myHeader

    })
    .then(res => res.json())
    .then(
        (result) => {
            this.setState({
                isDeleteCustomer:false
            })
        },(error) => {
            this.setState({ error });
        }
    )
}

render() {

    let form;
    if(this.state.isAddCustomer && !this.state.isEditCustomer){
        console.log("Add")
        form = <AddCustomer onAddFormSubmit={this.onAddFormSubmit}
        isAddCustomer = {this.state.isAddCustomer}
        onFormControl = {this.onFormControl}/>
    }else if(this.state.isEditCustomer && !this.state.isAddCustomer){
        console.log("Edit")
        form = <AddCustomer onAddFormSubmit={this.onAddFormSubmit}
        singleCustomer = {this.state.singleCustomer}
        onFormControl = {this.onFormControl}/>
    }else if(this.state.isDeleteCustomer){
        console.log("Delete")
        console.log(this.state.deleteId)
        form = <DeleteRecord onDeleteCustomer={this.onDeleteCustomer}
        deleteId = {this.state.deleteId}
        />
    }

    return (
        <div>
            {form}
            <br/>
            <CustomerView 
                onEditCustomer = {this.onEditCustomer} 
                onCreate = {this.onCreate} 
                onDeleteClick = {this.onDeleteClick}/>
        </div>
    )
}

}

Вот CustomerView. js

import React from 'react';
import { Table, Button } from 'semantic-ui-react';

export default class CustomerView extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        error: null,
        deleteTitle: "customer",
        isLoaded: false,
        formClose: false,
        singleCustomer: [],
        users: []
    }
}

//fetch data 
componentDidMount() {

    const customerApi = 'https://localhost:44387/api/Customers';

    const myHeader = new Headers();
    myHeader.append('Content-type', 'application/json');
    myHeader.append('Accept', 'application/json');
    myHeader.append('Origin', 'https://localhost:44387');

    const options = {
        method: 'GET',
        myHeader
    };

    fetch(customerApi, options)
        .then(res => res.json())
        .then(
            (result) => {
                this.setState({
                    users: result,
                    isLoaded: true
                });
            },
            (error) => {
                this.setState({
                    isLoaded: false,
                    error
                });
            }
        )
}

//Delete Customer

onDeleteCustomer = customerId => {

    const { users } = this.state;
    this.setState({
        users: users.filter(customer => customer.customerId !== customerId)
    });

    const customerApi = 'https://localhost:44387/api/Customers/' + customerId;

    const myHeader = new Headers({
        'Accept': 'application/json',
        'Content-type': 'application/json; charset=utf-8'
    });

    fetch(customerApi, {
        method: 'DELETE',
        headers: myHeader

    })
        .then(res => res.json())
        .then(
            (result) => {
                this.setState({

                })
            }, (error) => {
                this.setState({ error });
            }
        )
}

render() {
    const { users } = this.state;

    return (
        <div>

            <Button color='blue' onClick={() => this.props.onCreate()}>New Customer</Button>
            <br/>
            <br/>
            <Table celled textAlign='center'>
                <Table.Header>
                    <Table.Row>
                        <Table.HeaderCell>ID</Table.HeaderCell>
                        <Table.HeaderCell>Name</Table.HeaderCell>
                        <Table.HeaderCell>Address</Table.HeaderCell>
                        <Table.HeaderCell>Action</Table.HeaderCell>
                        <Table.HeaderCell>Action</Table.HeaderCell>
                    </Table.Row>
                </Table.Header>

                <Table.Body >
                    {
                        users.map(user => (
                            <Table.Row key={user.customerId}>

                                <Table.Cell>{user.customerId}</Table.Cell>
                                <Table.Cell>{user.name}</Table.Cell>
                                <Table.Cell>{user.address}</Table.Cell>

                                <Table.Cell>
                                    <Button color='blue' onClick={() => 
  this.props.onEditCustomer(user.customerId)}>Edit</Button>
                                </Table.Cell>

                                <Table.Cell>
                                    <Button color='red' onClick={() => 
 this.props.onDeleteClick(user.customerId)}>Delete</Button>
                                </Table.Cell>

                            </Table.Row>
                        ))
                    }
                </Table.Body>

                <Table.Footer>
                    <Table.Row>
                        <Table.HeaderCell colSpan='5'>
                            No of Pages
                    </Table.HeaderCell>
                    </Table.Row>
                </Table.Footer>
            </Table>

        </div>
    )
}

}

Вот AddCustomer. js

import React from 'react';
import { Button, Form, Modal } from 'semantic-ui-react';

export default class AddCustomer extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        showCreateForm: false,
        addOrdit:false,
        id: "",
        name: "",
        address: "",
        formData: {},
        record: {}
    }
    if (props.isAddCustomer){
        this.state.showCreateForm = props.isAddCustomer;
    }
    else if (props.singleCustomer) {
        console.log("Single customer")
        console.log(props.singleCustomer)
        this.state.id = props.singleCustomer.customer.customerId;
        this.state.name = props.singleCustomer.customer.name;
        this.state.address = props.singleCustomer.customer.address;
        this.state.record = props.singleCustomer.customer;
        this.state.showCreateForm = props.singleCustomer.isEditCustomer;
        this.state.addOrdit = props.singleCustomer.isEditCustomer;
        console.log(this.state.name)

    }else if(props.closeForm){
        this.state.showCreateForm = props.closeForm;
    }

}

handleChangeName = event => {
    const value = event.target.value;
    this.setState({ name:value });
}

handleChangeAddress = event => {
    const value = event.target.value;
    this.setState({ address:value });
}

handleSubmit = event => {
    event.preventDefault();
    if(this.state.addOrdit){

        this.setState({
            record: {
                customerId: this.state.id,
                name: this.state.name, 
                address: this.state.address
            }
        });
    this.props.onAddFormSubmit(this.state.record);

    }else{
        this.setState({
            formData: {
                name: this.state.name, 
                address: this.state.address
            }
        });
        this.props.onAddFormSubmit(this.state.formData);
    }


}

//On cancel button click close Create user form
closeCreateForm = () => {
    this.setState({ showCreateForm: false })
    this.props.onFormControl();
}

//Open Create new Customer form
openCreateCustomer = () => {
    this.setState({ showCreateForm: true })
}

render() {

    let formTitle;
    if (this.state.id !== 0) {
        formTitle = "Edit Customer";
    } else {
        formTitle = "New Customer";
    }

    return (
        <div>
            <Modal size='small' 
            closeOnTriggerMouseLeave={false} 
            open={this.state.showCreateForm}>
                <Modal.Header>
                    {formTitle}
                </Modal.Header>
                <Modal.Content>
                    <Form onSubmit={this.handleSubmit}>

                        <Form.Field>
                            <label>Name</label>
                            <input type="text" placeholder='Name' name="name"
                                value={this.state.name}
                                onChange={this.handleChangeName} />
                        </Form.Field>

                        <Form.Field>
                            <label>Address</label>
                            <input type="text" placeholder='Address' name="address"
                                value={this.state.address}
                                onChange={this.handleChangeAddress} />
                        </Form.Field>

                        <br />
                        <Button type='submit' floated='right' color='green'>Create</Button>
                        <Button floated='right' onClick={this.closeCreateForm} 
  color='black'>Cancel</Button>
                        <br />
                    </Form>

                </Modal.Content>
            </Modal>

        </div>
    )
}

}

И последний DeleteRecord. js

import React from 'react';
import { Button, Modal, Icon } from 'semantic-ui-react';

export default class DeleteRecord extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        ID:'',
        title: "",
        open: false
    }
    if(props.deleteId){
        console.log(props.deleteId)
        this.state.ID = props.deleteId.ID;
        this.state.title = props.deleteId.title;
        this.state.open = props.deleteId.open;
    }

}

//On cancel button click close Create user form
closeCreateForm = () => {
    console.log("Clicked")
    this.setState({ open: false })
}

//Open Create new Customer form
openCreateCustomer = () => {
    this.setState({ open: true })
}

render() {
    const title = "Delete " + this.state.title;

    return (
        <div>
            <Modal size='small' 
            closeOnTriggerMouseLeave={false} 
            open={this.state.open}>
                <Modal.Header>
                    {title}
                </Modal.Header>
                <Modal.Content>
                    <br />

                    Are you sure?

                    <br />
                    <br />
                    <Button floated='right' icon labelPosition='right' color='red'
                        value='true'
                        onClick={() => this.props.onDeleteCustomer(this.state.ID)}
                    >
                        <Icon name='close' />
                        Delete
                    </Button>
                    <Button floated='right' color='black'
                        value='false'
                        onClick={this.closeCreateForm}
                    >Cancel</Button>

                    <br />
                    <br />
                </Modal.Content>
            </Modal>
        </div>
    )
}

}
...