Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
95 views
in Technique[技术] by (71.8m points)

c# - How to send post data from React frontend to .NET backend

I have a webpage where a user signs up to become a user by filling out four textboxes and clicking submit. When they click submit, an api call is fired and sends that data to my controller. It then takes that data and maps it to the columns from my model, where it is then added to the DbSet. I am getting the error Cannot insert the value NULL into column 'email', table 'IssueTrackerDB.dbo.Users'; column does not allow nulls. INSERT fails. Keep in mind I am entering values for all four textboxes when I test it, so email isn't getting left out. Also, do I have to provide names or ids for each textbox in the frontend, so it maps to my model successfully?

Value of Users object after it is created Value of Users object after it is created

React Frontend

import React, { Component } from "react";
import { useState } from "react";
import { Grid, TextField, Button, Typography } from "@material-ui/core";

const Signup = () => {
    const [username, setUsername] = useState();
    const [password, setPassword] = useState();
    const [email, setEmail] = useState();
    const [role, setRole] = useState()

    const post = () => {
        const requestOptions = {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
                username: username,
                password: password,
                email: email,
                role: role
            }),
            
        };
        fetch("https://localhost:5001/api/IssueTracker", requestOptions)
            .then((response) => response.text())
            .then((data) => {
               

            })
    }

    return (
        <div>
            <body>
                <form action="#" method="POST">
                    <TextField onChange={(e) => setUsername(e.target.value)}> </TextField>
                    <br>
                    </br>
                    <TextField onChange={(e) => setPassword(e.target.value)}> </TextField>
                    <br>
                    </br>
                    <TextField onChange={(e) => setEmail(e.target.value)}> </TextField>
                    <br>
                    </br>
                    <TextField onChange={(e) => setRole(e.target.value)}> </TextField>
                    <br>
                    </br>
                    <Button onClick={() => post()}> Sign Up</Button>
                </form>
            </body>
        </div>
    );
}



export default Signup;

Controller

// POST api/values
        [HttpPost]
        public void Post(Users user)
        {
            _repository.CreateUser(user);
            _repository.SaveChanges();
        }

Model

namespace IssueTracker.Models
{
    public class Users
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public string id { get; set; }

        [Required]
        public string username { get; set; }

        [Required]
        public string password { get; set; }

        [Required]
        public string email { get; set; }

        [Required]
        public string role { get; set; }

        public Users(string username, string password, string email, string role)
        {
            this.username = username;
            this.password = password;
            this.email = email;
            this.role = role;
        }

        public Users()
        {

        }

    }
}

Interface

using IssueTracker.Models;

namespace IssueTracker.Data
{
    public interface IIssueTrackerRepo
    {
        bool SaveChanges();
        //IEnumerable<Command> GetAllCommands();
        //Command GetCommandById(int id);
        void CreateUser(Users cmd);
        //void UpdateCommand(Command cmd);
        //void DeleteCommand(Command cmd);
    }
}

Interface Implementation

using System;
using IssueTracker.Models;
namespace IssueTracker.Data
{
    public class SqlUsersRepo: IIssueTrackerRepo
    {
        private readonly UsersContext _context;

        public SqlUsersRepo(UsersContext context)
        {
            _context = context;
        }

        public void CreateUser(Users user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            
            _context.Users.Add(user);
        }

        public bool SaveChanges()
        {
            return (_context.SaveChanges() >= 0);
        }
    }
}

UsersContext Class

using IssueTracker.Models;
using Microsoft.EntityFrameworkCore;
namespace IssueTracker.Data
{
    public class UsersContext : DbContext
    {
        public UsersContext()
        {
        }

        public UsersContext(DbContextOptions<UsersContext> opt) : base(opt)
        {
        }

        public DbSet<Users> Users { get; set; }
    }

}
question from:https://stackoverflow.com/questions/65878440/how-to-send-post-data-from-react-frontend-to-net-backend

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. Apply the [FromBody] attribute to a parameter to populate its properties from the body of an HTTP request. The ASP.NET Core runtime delegates the responsibility of reading the body to an input formatter.
  2. You can read this article or MSDN

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...