Надеюсь, вы хорошо в этом сезоне
Сейчас я занимаюсь сборкой приложения MVC с помощью Visual Studio и подключаю его к базе данных SQL и использую: React JS компоненты должны быть написанным с использованием классов ES6 и jsx Create управляемых компонентов. Используйте состояние. Используйте AJAX внутри компонентов React для отправки / получения от контроллера
У меня проблема с получением данных из базы данных для просмотра таблицы. Не могли бы вы взглянуть на мой код
Когда я запускаю его, он загружает данные, но не отображается в таблице, как на это изображение
Я проверил инспектировать element / console и написано:
Предупреждение: каждый дочерний элемент в списке должен иметь уникальное свойство «key».
Проверьте метод рендеринга Customer
.
in TableRow (created by Customer)
in Customer
in div
CustomerIndex.jsx
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Button, Modal, Header, Image, Container, Divider, Grid, Menu, Segment, Icon, Popup, Form, Table, Label } from 'semantic-ui-react';
import $ from 'jquery';
{/* Model class customer */ }
class Customer extends React.Component {
constructor(props) {
super(props);
this.state = {
customerList: []
};
this.loadData = this.loadData.bind(this);
this.add = this.add.bind(this);
this.update = this.update.bind(this);
this.delete = this.delete.bind(this);
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
this.loadData();
}
loadData() {
$.ajax({
url: "/Customer/GetCustomersDetails",
dataType: 'json',
type: 'get',
contentType: 'application/json',
processData: false,
beforeSend: function () { // loading...
$("#loading").show();
}
}).done((data) => {
$("#loading").hide();
this.setState({
customerList: data
})
});
//fetch("/Customer/GetCustomersDetails")
// .then(response => response.json())
// .then(data => {
// this.setState({ customerList: data });
// });
}
add(event) {
// ajax call logic
const formData = new FormData(event.target)
let dataJSON = {}
event.preventDefault()
for (let entry of formData.entries()) {
dataJSON[entry[0]] = entry[1]
}
console.log(dataJSON)
fetch("/Customer/PostAddOneCustomer", {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(dataJSON)
}).then(response => {
response.json().then(data => {
console.log(data);
window.location.reload();
})
})
}
handleChange(e) {
this.setState({
[e.target.name]: e.target.value
})
}
update(id) {
//ajax call logic
var data = {
name: this.state.name,
address: this.state.address,
id: id
}
$.ajax({
url: "/Customer/PostUpdateOneCustomer",
dataType: 'json',
type: 'post',
contentType: 'application/json',
data: JSON.stringify(data)
}).done((data) => {
console.log(data);
this.setState({
serviceList: data
})
});
}
delete(id) {
//ajax call logic
$.ajax({
url: "/Customer/DeleteOneCustomer?customerId=" + id,
type: 'POST',
dataType: 'JSON',
success: function (response) {
NotificationManager.success('Success message', 'Title here');
window.location.reload(); // refresh the page
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
render() {
let customerList = this.state.customerList;
let tableData;
console.log(customerList);
return (
<React.Fragment>
<div>
<Modal id="modal" trigger={<Button color="green">Add a new customer</Button>} >
<Modal.Header >Add a new customer</Modal.Header>
<Modal.Content>
<Form onSubmit={this.add} ref="form" method="POST">
<Form.Field>
<label>Name</label><br />
<input type="text" placeholder="Type a name" name="name" required
minlength="3" maxlength="20" /><br />
</Form.Field>
<Form.Field>
<label>Address</label><br />
<input placeholder="Type an address" name="address" required /><br />
</Form.Field>
<Button type='submit'><Icon name="save" />save</Button>
</Form>
</Modal.Content>
</Modal>
<Table celled>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Customer name</Table.HeaderCell>
<Table.HeaderCell>Address</Table.HeaderCell>
<Table.HeaderCell>Action (Edit)</Table.HeaderCell>
<Table.HeaderCell>Action (Delete)</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{ customerList.map(service =>
<Table.Row key={service.Id}>
<Table.Cell >{service.Name}</Table.Cell>
<Table.Cell >{service.Address}</Table.Cell>
<Table.Cell >
<Modal id="modal" trigger={<Button color="yellow" ><Icon name="edit" />Edit</Button>} >
<Modal.Header >Details customer</Modal.Header>
<Modal.Content>
<Form ref="form" method="POST" onSubmit={this.update.bind(this, service.Id)}>
<Form.Field>
<label>Name</label><br />
<input type="text" placeholder="Type a name" name="name" placeholder={service.Name}
onChange={this.handleChange} required minlength="3" maxlength="20" /><br />
</Form.Field>
<Form.Field>
<label>Address</label><br />
<input placeholder="Type an address" name="address" placeholder={service.Address} onChange={this.handleChange} required /><br />
</Form.Field>
<Button type='submit'><Icon name="save" />save</Button>
</Form>
</Modal.Content>
</Modal>
</Table.Cell>
<Table.Cell>
<Button color="red" onClick={this.delete.bind(this, service.Id)}><Icon name="trash" />Delete</Button>
</Table.Cell>
</Table.Row>
)}
</Table.Body>
<Table.Footer>
</Table.Footer>
</Table>
</div>
<div id="loading"><p>Loading...</p></div>
</React.Fragment>
)
}
}
{/* rendering the component */ }
const app = document.getElementById('customers');
ReactDOM.render(<div><h1 className="anim">Customer Details</h1><Customer /></div>, app);
CustomerController.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CRUDOnboardingReactJS.Models;
namespace CRUDOnboardingReactJS.Controllers
{
public class CustomerController : Controller
{
private CRUDOnboardingEntities1 db = new CRUDOnboardingEntities1();
// GET: Customer
public ActionResult Index()
{
return View();
}
// JSON
[HttpGet]
public JsonResult GetCustomersDetails()
{
var customers = db.Customers.Select(c => new { c.Id, c.Name,c.Address }).ToList();
//return Json(db.Customers.ToList());
// if (db.Customers != null)
// {
List<Object> array = new List<Object>() { customers};
return Json(array, JsonRequestBehavior.AllowGet);
// return Json(db.Customers.ToList(), JsonRequestBehavior.AllowGet);
//}
//return Json(db.Customers.ToList(), JsonRequestBehavior.DenyGet);
}
public JsonResult PostAddOneCustomer(Customer customer)
{
if (ModelState.IsValid) // checking the fields are completed
{
var query = db.Customers.Add(new Customer() { Name = customer.Name, Address = customer.Address });
db.SaveChanges();
return Json(db.Customers.ToList(), JsonRequestBehavior.AllowGet);
}
return Json(db.Customers.ToList(), JsonRequestBehavior.DenyGet);
}
public JsonResult PostUpdateOneCustomer(Customer customer)
{
if (ModelState.IsValid)
{
try
{
var query = db.Customers.Where(user => user.Id == customer.Id).Select(col => new { col.Name, col.Address }).Single();
query = new { customer.Name, customer.Address };
db.Entry(customer).State = EntityState.Modified; // allow to update the entity
db.SaveChanges();
return Json(db.Customers.ToList(), JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
return Json(db.Customers.ToList(), JsonRequestBehavior.DenyGet);
}
public JsonResult DeleteOneCustomer(int customerId)
{
var delete = from customer in db.Customers
join prodsold in db.ProductSolds on customer.Id equals prodsold.CustomerId
where customer.Id == customerId && prodsold.CustomerId == customerId
select prodsold;
foreach (var record in delete)
{
db.ProductSolds.Remove(record);
}
var c = db.Customers.Where(user => user.Id == customerId).Single(); // delete the customer
db.Customers.Remove(c);
db.SaveChanges();
return Json(db.Customers.ToList(), JsonRequestBehavior.AllowGet);
}
}
}