Существует метод showUpdateModal для извлечения данных, и для рендеринга детали должно отображаться это значение по умолчанию. - PullRequest
0 голосов
/ 19 октября 2019

Я создал компонент Edit, используя React и Semantic-ui, модальные в этой базовой структуре Asp.Net. Когда я нажимаю кнопку «Изменить», отображается модальное значение, но значения по умолчанию, соответствующие этой записи, не отображаются во входных тегах.

This is code to the fetch customer data that consist of all the methods related to edit component

import React from 'react';
import ReactDOM from 'react-dom';

import EditCustomer from './EditCustomer';
import {  Button } from 'semantic-ui-react';
import 'semantic-ui-css/semantic.min.css';

import $ from 'jquery';

export class FetchCustomer extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            customerList: [], success: { Data: '' },
            showCreateModal: false, CustomerId: '', CustomerName: '', CustomerAddress: '', showUpdateModal: false,
            updateId: 0,
            Success: [], errors: {}


        };

       //binding the methods 
        this.showUpdateModal = this.showUpdateModal.bind(this);
        this.closeUpdateModal = this.closeUpdateModal.bind(this);


        this.onChange = this.onChange.bind(this);

    }




    showUpdateModal(id) {
        //alert(id.CName);
        this.setState({ showUpdateModal: true });
        this.setState({ updateId: id });

//ajax call to get the object from controller this has some issue 
        $.ajax({
            url: "/Customer/Details/{id}",
            type: "GET",
            data: { id: id },
            success: function (data) {

                this.setState({
                    CustomerId: this.cid,
                    CustomerName: this.cname,
                    CustomerAddress: this.caddress,

                })

            }.bind(this)

        })

    }


// closeupdatemodal to close modal when user click cancel
    closeUpdateModal() {
        this.setState({ showUpdateModal: false });
        window.location.reload()
    }

    onChange(e) {
        this.setState({ [e.target.name]: e.target.value });
    }

    render() {

        let list = this.state.customerList;
        var tableData = null;
        if (list != " ") {
            // display data while fetching 
            tableData = list.map((lists, index) =>
                <tr key={lists.cid}>
                    <td className="two wide">{lists.cname}</td>
                    <td className="two wide">{lists.caddress}</td>
                    <td className="four wide">
                        <Button className="ui yellow button" onClick={this.showUpdateModal.bind(this, lists.cid)}><i className="edit icon"></i>EDIT</Button>
                    </td>





                </tr>

            )
        }
        return (

            <React.Fragment>
                <div>



                    <EditCustomer onChange={this.onChange} update={this.state.updateId}
                        onClose={this.closeUpdateModal} onEditSubmit={this.onEditSubmit}
                                showUpdateModal={this.state.showUpdateModal}
                        Id={this.state.CustomerId} Name={this.state.CustomerName}
                        Address={this.state.CustomerAddress} errors={this.state.errors} />




}}

This is code for Edit component of react application


import React from 'react';
import $ from 'jquery';
import { Modal, Button, Form } from 'semantic-ui-react';
export default class EditCustomer extends React.Component {
    constructor(props) {
        super(props);
        this.state = { CustomerId:'',CustomerName:'', CustomerAddress:''

        };

        this.onClose = this.onClose.bind(this);
        this.onEditSubmit = this.onEditSubmit.bind(this);
    }
    onEditSubmit() {
        if (this.validateForm()) {

            let data = { 'CId': this.state.CustomerId, 'CName': this.state.CustomerName, 'CAddress': this.state.CustomerAddress };
            $.ajax({
                url: "/Customer/Edit",
                type: "POST",
                data: data,
                success: function (data) {
                    this.setState({ Success: data })
                    window.location.reload()
                }.bind(this)
            });
        }
    }
    validateForm() {
        let errors = {}
        let formIsValid = true;
        if (!this.state.CustomerName) {
            formIsValid = false;
            errors['CustomerName'] = 'please enter customer name';
        }
        if (typeof this.state.CustomerName !== "undefined") {
            if (!this.state.CustomerName.match(/^[a-zA-Z ]*$/)) {
                formIsValid = false;
                errors["CustomerName"] = "*Please enter only alphabet characters.";
            }
        }

        if (!this.state.CustomerAddress) {
            formIsValid = false;
            errors['CustomerAddress'] = '*Please enter the Customer Address'
        }

        this.setState({
            errors: errors
        });
        return formIsValid;
    }
    onClose() {
        this.setState({ showUpdateModal: false });
        window.location.reload()
    }

    render() {
        return (
            <React.Fragment>
                <Modal open={this.props.showUpdateModal} onClose={this.props.onClose} size='small'>
                    <Modal.Header> Edit Customer </Modal.Header>
                    <Modal.Content>
                        <Form>
                            <Form.Field>
                                <label>Name</label>
                                <input type="text" name="CustomerName" 
  placeholder='Name' defaultValue={this.props.CustomerName} onChange= 
 {this.props.onChange} />
                                <div style={{ color: 'red' }}>
                                    {this.props.errors.CustomerName}
                                </div>
                            </Form.Field>
                            <Form.Field>
                                <label>Address</label>
                                <input type="text" name="CustomerAddress" 
  placeholder='Address' defaultValue={this.state.value} onChange= 
   {this.props.onChange} />

<div style={{ color: 'red' }}>
 {this.props.errors.CustomerAddress} </div>
                            </Form.Field>
                        </Form>
                    </Modal.Content>
                    <Modal.Actions>
                        <Button onClick={this.props.onClose} secondary >Cancel
                        </Button>
                        <Button onClick={this.props.onEditSubmit} className="ui green button">Edit
                        <i className="check icon"></i>
                        </Button>
                    </Modal.Actions>
                </Modal>
            </React.Fragment>
        )
    }
}

Я хочу отобразить значения записи, когда пользователь нажимает кнопку «Изменить», например «Имя» и «Адрес» в модальном режиме.

...