首页 > 解决方案 > 如何从 ReactJS 将数据发布到 ASP.NET Core

问题描述

我想在 ASP.Net Core 端接收我在 React JS 中创建的 Form 信息,然后我将连接 ASP.Net Core 和 Firebase 并将数据移动到数据库中。

但首先,我如何才能在 ASP.Net Core 中获取我在 React JS 端输入的信息?请问可以分享资源吗?

我已经在 ASP 端完成了一些代码编写,但是如何使用 React JS 来完成呢?我需要在 React JS 端发出 HTTP 请求。

先感谢您。

VendorRegistrationController.cs

namespace BaitForm.Controllers
{

[Produces("application/json")]
[Route("api/controller")]
[ApiController]
[EnableCors("ReactPolicy")]

public class VendorRegistrationController : ControllerBase
{
    private readonly VendorRegistrationService vendorRegistrationService;

    public VendorRegistrationController(VendorRegistrationService vendorRegistrationService)
    {
        this.vendorRegistrationService = vendorRegistrationService;
    } 

    [HttpGet]
    public IEnumerable<VendorRegistration> Get()
    {
        return vendorRegistrationService.GetAll();
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> Get(int id)
    {
        return Ok(vendorRegistrationService.GetById(id));
    }

    [HttpPost]
    public async Task<IActionResult> Post([FromBody] VendorRegistration vendorRegistration)
    {
        return CreatedAtAction("Get", new { id = vendorRegistration.VendorCustomerID }, vendorRegistrationService.Create(vendorRegistration)));
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> Put(int id, [FromBody] VendorRegistration vendorRegistration)
    {
        vendorRegistrationService.Update(id, vendorRegistration);
        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(int id)
    {
        vendorRegistrationService.Delete(id);
        return NoContent();
    }

    public override NoContentResult NoContent()
    {
        return base.NoContent();
    }
  }
 }

供应商注册.cs

 namespace BaitForm.Models
 {
  public class VendorRegistration
   {
    public long VendorCustomerID { get; set; }
    public string VendorFirstName { get; set; }
    public string VendorLastName { get; set; }
    public string VendorEmail { get; set; }
    public int VendorPassword { get; set; }
    public string VendorCompanyName { get; set; }
    public string VendorCountry { get; set; }
    public string VendorState { get; set; }
    public string VendorAdressLine1 { get; set; }
    public string VendorAdressLine2 { get; set; }
    public string VendorZipCode { get; set; }
    public long VendorPhoneNumber { get; set; }

    public VendorRegistration()
    {}
  }
  }

VendorRegistrationService.cs

 namespace BaitForm.Services
{
 public class VendorRegistrationService
 {
    private static List<VendorRegistration> vendorRegistrationList = new List<VendorRegistration>();
    private static int Count = 1;
    private static readonly string[] names = new string[] { "names", "names2", "names3" };

    static VendorRegistrationService()
    {
        Random rnd = new Random();
        for(int i= 0; i<5; i++)
        {
            VendorRegistration vendorRegistration = new VendorRegistration
            {
                VendorCustomerID = Count,
                VendorCompanyName = names[Count++]
            };

            vendorRegistrationList.Add(vendorRegistration);
        }
    }

    public List<VendorRegistration> GetAll()
    {
        return vendorRegistrationList.OrderBy(a => a.VendorCustomerID).ToList();
    }

    public VendorRegistration GetById(int id)
    {
        return vendorRegistrationList.Where(x => x.VendorCustomerID == id).FirstOrDefault();
    }

    public VendorRegistration Create(VendorRegistration vendorRegistration)
    {
        vendorRegistration.VendorCustomerID = Count++;
        vendorRegistrationList.Add(vendorRegistration);
        return vendorRegistration;
    }

    public void Update(int id, VendorRegistration vendorRegistration)
    {
        VendorRegistration vendorRegistrationUpdate = vendorRegistrationList.Where(y => y.VendorCustomerID == id).FirstOrDefault();
        vendorRegistrationUpdate.VendorCustomerID = vendorRegistration.VendorCustomerID;
        vendorRegistrationUpdate.VendorCompanyName = vendorRegistration.VendorCompanyName;
    }

    public void Delete(int id)
    {
        vendorRegistrationList.RemoveAll(z => z.VendorCustomerID == id);
    }
       }
    }

React JS 端 组件 RegistrationForm.tsx

 const RegistrationForm = () => {
    const [sameAsShipping, setSameAsShipping] = useState(false)
    const router = useRouter()
    const classes = useStyles()
    const bull = <span className={classes.bullet}>•&lt;/span>


 const handleFormSubmit = async (values: any) => {
   console.log(values)
   router.push('/payment')
 }

const handleCheckboxChange =
  (values: typeof initialValues, setFieldValue: any) => (e: any, _: boolean) => {
  const checked = e.currentTarget.checked

  setSameAsShipping(checked)
  setFieldValue('same_as_shipping', checked)
  setFieldValue('billing_name', checked ? values.shipping_name : '')
}



  return (
    <Formik
      initialValues={initialValues}
      validationSchema={checkoutSchema}
      onSubmit={handleFormSubmit}
    >
    {({
      values,
      errors,
      touched,
    handleChange,
    handleBlur,
    handleSubmit,
    setFieldValue,
  }) => (
    <form onSubmit={handleSubmit}>
      <Card1 sx={{ mb: '2rem' }}>
       <Typography  variant="h4" align="center" fontWeight="800" mb={2}>
          Create Your Vendor Account
       </Typography>

        <Typography fontWeight="600" mb={2}>
          Account Info
        </Typography>

        <Grid container spacing={6}>
          <Grid item sm={6} xs={12}>
            <TextField
              name="first_name"
              label="First Name*"
              fullWidth
              sx={{ mb: '1rem' }}
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.first_name || ''}
              error={!!touched.first_name && !!errors.first_name}
              helperText={touched.first_name && errors.first_name}
            />
            <TextField
              name="vendor_name"
              label="Company Name*"
              fullWidth
              sx={{ mb: '1rem' }}
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.vendor_name || ''}
              error={!!touched.vendor_name && !!errors.vendor_name}
              helperText={touched.vendor_name && errors.vendor_name}
            />
            <TextField
              name="password"
              label="Password*"
              fullWidth
              sx={{ mb: '1rem' }}
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.password || ''}
              error={!!touched.password && !!errors.password}
              helperText={touched.password && errors.password}
            />
            <Autocomplete
              options={countryList}
              getOptionLabel={(option) => option.label || ''}
              value={values.shipping_country}
              sx={{ mb: '1rem' }}
              fullWidth
              onChange={(_e, value) => setFieldValue('shipping_country', value)}
              renderInput={(params) => (
                <TextField
                  label="Country"
                  placeholder="Select Country"
                  variant="outlined"
                  size="small"
                  error={!!touched.shipping_country && !!errors.shipping_country}
                  helperText={
                    touched.shipping_country && errors.shipping_country
                  }
                  {...params}
                />
              )}
            />
            <TextField
              name="address1"
              label="Address Line 1*"
              fullWidth
              sx={{ mb: '1rem' }}
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.address1 || ''}
              error={!!touched.address1 && !!errors.address1}
              helperText={touched.address1 && errors.address1}
            />
            <TextField
              name="zip_code"
              label="Zip Code*"
              type="number"
              fullWidth
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.zip_code || ''}
              error={!!touched.zip_code && !!errors.zip_code}
              helperText={touched.zip_code && errors.zip_code}
            />
            
          </Grid>
          <Grid item sm={6} xs={12}>
             <TextField
              name="last_name"
              label="Last Name*"
              fullWidth
              sx={{ mb: '1rem' }}
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.last_name || ''}
              error={!!touched.last_name && !!errors.last_name}
              helperText={touched.last_name && errors.last_name}
            />
            <TextField
              name="email_address"
              label="Email Address*"
              type="email"
              fullWidth
              sx={{ mb: '1rem' }}
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.email_address || ''}
              error={!!touched.email_address && !!errors.email_address}
              helperText={touched.email_address && errors.email_address}
            />
            <TextField
              name="confirm_password"
              label="Confirm Password*"
              fullWidth
              sx={{ mb: '1rem' }}
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.confirm_password || ''}
              error={!!touched.confirm_password && !!errors.confirm_password}
              helperText={touched.confirm_password && errors.confirm_password}
            />
             <TextField
              name="state"
              label="State*"
              fullWidth
              sx={{ mb: '1rem' }}
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.state || ''}
              error={!!touched.state && !!errors.state}
              helperText={touched.state && errors.state}
            />
            <TextField
              name="address2"
              label="Address Line 2*"
              fullWidth
              sx={{ mb: '1rem' }}
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.address2 || ''}
              error={!!touched.address2 && !!errors.address2}
              helperText={touched.address2 && errors.address2}
            />
            <TextField
              name="phone_number"
              label="Phone Number"
              fullWidth
              onBlur={handleBlur}
              onChange={handleChange}
              value={values.phone_number || ''}
            />
          </Grid>
        </Grid>
      </Card1>

      <Card1 sx={{ mb: '2rem' }}>
        <Typography fontWeight="600" mb={2}>
          Additional Information / Accept Terms
        </Typography>

        {!sameAsShipping && (
          <Grid container spacing={6}>
            <Grid item sm={6} xs={12}>
            <Autocomplete
                options={countryList}
                getOptionLabel={(option) => option.label || ''}
                value={values.billing_country}
                sx={{ mb: '1rem' }}
                fullWidth
                onChange={(_e, value) => setFieldValue('billing_country', value)}
                renderInput={(params) => (
                  <TextField
                    label="Shop Type"
                    placeholder="Shop Type"
                    error={!!touched.billing_country && !!errors.billing_country}
                    helperText={
                      touched.billing_country && errors.billing_country
                    }
                    {...params}
                  />
                )}
              />
              <Autocomplete
                options={countryList}
                getOptionLabel={(option) => option.label || ''}
                value={values.billing_country}
                sx={{ mb: '1rem' }}
                fullWidth
                onChange={(_e, value) => setFieldValue('billing_country', value)}
                renderInput={(params) => (
                  <TextField
                    label="I'm interested in learning more about..."
                    placeholder="I'm interested..."
                    error={!!touched.billing_country && !!errors.billing_country}
                    helperText={
                      touched.billing_country && errors.billing_country
                    }
                    {...params}
                  />
                )}
              />
              <TextField
                name="billing_contact"
                label="How did your hear about BaitMrkt?"
                fullWidth
                sx={{ mb: '1rem' }}
                onBlur={handleBlur}
                onChange={handleChange}
                value={values.billing_contact || ''}
                error={!!touched.billing_contact && !!errors.billing_contact}
                helperText={touched.billing_contact && errors.billing_contact}
              />
              <Grid container sx={{mt: '4rem'}}>
                <FormControlLabel
                 label={
                  <FlexBox>
                    I agree to the BaitMrkt
                      <H6 ml={1} color= "#D11C25">
                        Terms & Conditions
                      </H6>
                      <Span ml={1}>
                      and
                      </Span>
                    <H6 ml={1} color= "#D11C25">
                    Privacy Policy*
                      </H6>
                  </FlexBox>
                }
                 control={<Checkbox size="small" color="secondary" />}
                 sx={{
                  zIndex: 1,
                  position: 'relative',
                 }}
                 onChange={handleCheckboxChange(values, setFieldValue)}
                />
          
              </Grid>

             <Grid container>
              <FormControlLabel
                 label={
                  <FlexBox>
                   I agree to receive account updates and other vendor specific
                   information via email.*
                  </FlexBox>
                }
                 control={<Checkbox size="small" color="secondary" />}
                 sx={{
                  zIndex: 1,
                  position: 'relative',
                }}
               onChange={handleCheckboxChange(values, setFieldValue)}
              /> 
        </Grid>      

            </Grid>
          </Grid>
        )}
        </Card1>


        <Grid container>
         <Grid item sm={6} xs={12}>
          <Button variant="contained" color="primary" type="submit">
            REGISTER
           </Button>
          </Grid>
        </Grid>

      </form>
     )}
   </Formik>
    )
    }


const initialValues = {
  shipping_name: '',
  shipping_email: '',
  shipping_contact: '',
  shipping_company: '',
  shipping_zip: '',
  shipping_country: countryList[229],
  shipping_address1: '',
  shipping_address2: '',
  }

const checkoutSchema = yup.object().shape({
  first_name: yup.string().required("required"),
  last_name: yup.string().required("required"),
  vendor_name: yup.string().required("required"),
  address1: yup.string().required("required"),
  address2: yup.string().required("required"),
  email_address: yup.string().email("invalid email").required("required"),
  password: yup.string().required("required"),
  confirm_password: yup.string().required("required"),
  state: yup.string().required("required"),
  zip_code: yup.string().required("required"),

  })

 export default RegistrationForm

在此处输入图像描述

标签: asp.netreactjsasp.net-coreasp.net-web-apixmlhttprequest

解决方案


推荐阅读