Tuesday, October 22, 2019

2-Add New Records in SQL-Server Table in React Js by using Default Template (Part-2)

Hello & As-salam u alikum ! , In this article we will learn to add new records in React js with asp.net core. 

Step# 1:  

https://dotnetcorecommunity.blogspot.com/2019/10/1-display-data-from-sql-server-table-in.html
         Watch Previous Part to fetch data from  controller to React js Component and display on View.





Step# 2:

Go to the controller ,In our case our controller name is EmployeeController which we had made in last article, so add a new action method in the controller ,below is the code for adding new record method. 


[HttpPost]

        public void Create(TblEmployee obj)

        {

            TblEmployee employee = new TblEmployee(); 


                employee.Department = obj.Department;

                employee.City = obj.City;

                employee.Gender = "Female";

                db.TblEmployee.Add(employee);

                db.SaveChanges();

}




the Above code represents an action result which will called from react component to add data.

Step# 3:

We do not want our user to move to a new page for adding new records , we will provide user a component on the top of the grid , so that he/she can add new records on the same page on which data is displayed.





now create a new file named as Create.js in component folder. 


Paste the following code in Create.js folder .
import React, { Component } from 'react';
 class Create extends Component {

        this.state =
            {
            Name: "a", City: "a", Department: "a", id: 0,
    }


    {


     {

         

     




        this.setState({ [e.target.name]: e.target.value }); //what ever you write ,it changes the state


    }



     {


        var obj = { EmployeeId: this.state.id, Name: this.state.Name, Department: this.state.Department, City: this.state.City };


        $.ajax({


            url: '/Employee/Create',

            data: obj,

            success: function (response)

            {

               

              

            },

            error: function (response)

            {





    // This will handle the submit form event.  



            return (<span> </span>);

        }

        else {



                    <div className="card-body">


                            

                            <form >

                                <div className="form-group">

                                    <label>Name:</label>

                                    <input type="text" onChange={this.textchange.bind(this)} className="form-control" id="Name" name="Name" />

                                </div>


                                    <label>City:</label>

                                    <input type="text" onChange={this.textchange.bind(this)}  className="form-control" id="City" name="City" />

                                </div>


                                    <label >Department:</label>

                                    <input type="text" onChange={this.textchange.bind(this)} className="form-control" id="Department" name="Department" />

                                </div>


                                    e.stopPropagation();

                                    e.preventDefault();

                                    this.AddRecord();

                                    this.props.parentcall(false);


                            </form>

                        </div>


                </div>


        }

    }





Step# 4:

We need to make some changes in our old code that we had done in fetchData.js



import React, { Component } from 'react';

import Create from "./Create";


const $ = window.$;

export class FetchData extends Component

{


 constructor(props)

 { 

     

    super(props);

     this.state =

         {

         forecasts: [], loading: true,

         Name: "a", City: "a", Department: "a", id: 0,

         createisvisible: false,

         createbuttontext: "Create New Post",

         skip: 0,

         take: 1,

         totalPost: 0,

         x: false


     };

     this.callbackFunction = this.callbackFunction.bind(this)

   //  this.UpdateTime();

  }



    callbackFunction = (data) => {

        this.setState({ createisvisible: data, createbuttontext: "Create New Post", x: true });

        

    };



     componentDidMount()

     {

         console.log("DID MOUNT CALLED");

         fetch('Employee/GetAllEmployees')

             .then(response => response.json())

             .then(data => {

                 this.setState({ forecasts: data, loading: false });

                 console.log(this.state.forecasts);

             });


      





        

    }


    componentWillUpdate() {


        fetch('Employee/GetAllEmployees')

            .then(response => response.json())

            .then(data => {

                this.setState({ forecasts: data, loading: false });

                console.log(this.state.forecasts);

            });



    }




    UpdateTime() {

        setInterval(() => {



            fetch('Employee/GetAllEmployees')

                .then(response => response.json())

                .then(data => {

                    this.setState({ forecasts: data, loading: false });

                    console.log(this.state.forecasts);

                });

            console.log("Refersh");




        }, 10000);

    }











    //textbox change event -----------------------


    textchange(e) {

        this.setState({ [e.target.name]: e.target.value }); //what ever you write ,it changes the state


        console.log(e.target.value);

    }


  




    render() {

   


        if (this.state.loading) {

            return <div>

                <img alt="Not Found" className="img img-responsive" src="Loader.gif" style={{ display: "block", marginLeft: "auto", marginRight: "auto" }} />

      

            </div>;


        }


        if (!this.state.forecasts.length) {

            return <div>No Records Found</div>;

        }



    return (

      <div>

           

            

            <div style={{ padding:"20px" }}> 

            <button className="btn btn-sm btn-info" onClick={e => {


                    let v = this.state.createisvisible;

                    if (v === false)

                    {

                        this.setState({ createisvisible: !v, createbuttontext: "Discard Post" });


                    }

                    else {

                        this.setState({ createisvisible: !v, createbuttontext: "Create New Post" });


                    }

                    

                }}>

                    {this.state.createbuttontext}

            </button>

            </div>

            <Create parentcall={this.callbackFunction} isvisible={this.state.createisvisible} />

          


            <table className='table table-striped'>

                <thead>

                    <tr>

                        <th>id</th>

                        <th>Name</th>

                        <th>City</th>

                        <th>Department</th>

                        <th>Edit</th>

                        <th>Delete</th>


                    </tr>

                </thead>

                <tbody>

                    {this.state.forecasts.map(forecast =>

                        <tr key={forecast.employeeId}>

                            <td>{forecast.employeeId}</td>

                            <td>{forecast.name}</td>

                            <td>{forecast.city}</td>

                            <td>{forecast.department}</td>

                            <td>



                                <button type="button" onClick={e =>

                                {

                                    this.setState({ Name: forecast.name, id: forecast.employeeId, name: forecast.name, City: forecast.city, Department: forecast.department });



                                }} className="btn btn-primary" data-toggle="modal" data-target="#myModal">

                                    Edit

                          </button>



                            </td>

                             <td>

                                <button type="button"  className="btn btn-danger">

                                    Delete

                          </button>


                             </td>




                           

                        </tr>

                    )}

                </tbody>

            </table>





           



      </div>

    );

    }


}








Conclusion: 


We are done with this module , now we will do edit and delete record in next article,Thank you for reading. Have a nice day.

0 Comments:

Post a Comment

Do not Add Spam links in the Comment Box

Subscribe to Post Comments [Atom]

<< Home