簡體   English   中英

如何使用 React.js 將數據傳遞給 MVC Controller?

[英]How to pass data to MVC Controller using React.js?

我正在做一個使用React.js作為前端和Asp.net MVC作為后端進程的項目。

現在我的查詢是我必須將用戶輸入值傳遞給 Controller 方法。 . 我用谷歌搜索了它,但沒有找到任何解決方案。

這是我的 Controller 方法:

// POST: LoginController/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(LoginModel objModel)
        {
            try
            {
                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

這是 React.js 代碼

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

export class Login extends Component {
    static displayName = Login.name;

    constructor(props) {
        super(props);
        this.state = { strToken: '', strMessage: '', strUserName: '', strPassword: '' };
        this.UserhandleChange = this.UserhandleChange.bind(this);
        this.PwdhandleChange = this.PwdhandleChange.bind(this);
        this.LoginClick = this.LoginClick.bind(this);
    }

    UserhandleChange(event) { this.setState({ strUserName: event.target.value }); }
    PwdhandleChange(event) { this.setState({ strPassword: event.target.value }); }

    LoginClick(event) {
        event.preventDefault();
        const data = new FormData();
        
        if (this.state.strUserName == "admin" && this.state.strPassword == "admin") {
            data.append("UserName", this.state.strUserName);
            data.append("Password", this.state.strPassword);

            var xhr = new XMLHttpRequest();
            xhr.open('post', this.props.Url, true);
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.onreadystatechange = function () {
                if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
                    // Do something on success
                }
            }
            xhr.send(data);
        }
        else {
            this.setState({
                strMessage: "InValid UserName/ Password"
            });
        }
    }

    render() {
        return (
            <form onSubmit={this.LoginClick}>
                <div class="container">
                    <label>UserName</label>
                    <br />
                    <input type="text" value={this.state.strUserName} onChange={this.UserhandleChange}></input>
                    <br />
                    <br />
                    <label>Password </label>
                    <br />
                    <input type="password" value={this.state.strPassword} onChange={this.PwdhandleChange}></input>
                    <br />
                    <br />
                    <button type="submit" className="btn btn-primary">Login &nbsp; </button>
                    <button type="reset" className="btn btn-danger">Cancel &nbsp; </button>
                    <br />
                    <br />
                    <p aria-live="polite">Note :  <strong>{this.state.strMessage}</strong></p>
                </div >
            </form>
        );
    }
}

ReactDOM.render(<Login url="https://localhost:44384/Login/Create" />, document.getElementById('root'));

我不知道該怎么做,如果有人知道請幫助我實現這一目標。

謝謝你。

您可以嘗試使用axios庫並像這樣發送 http POST 請求

axios.post('/login', {
    username: 'user@example.com',
    password: 'Test@123'
  })
  .then(function (response) {
    // login success
    console.log(response);
  })
  .catch(function (error) {
    // error handling
    console.log(error);
  });

官方文檔: https://axios-http.com/docs/post_example

您可以使用npm install axios命令添加 axios 庫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM