简体   繁体   English

如何使用 React.js 将数据传递给 MVC Controller?

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

I'm doing a project using React.js as Front End and Asp.net MVC as Back end Process.我正在做一个使用React.js作为前端和Asp.net MVC作为后端进程的项目。

Now my query is i have to pass user input values to Controller Method.现在我的查询是我必须将用户输入值传递给 Controller 方法。 . . I was googled it but i didn't find any solutions.我用谷歌搜索了它,但没有找到任何解决方案。

Here it is my Controller Method:这是我的 Controller 方法:

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

This is React.js Code这是 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'));

I don't Know how to do that if anyone knows please help me to achieve that.我不知道该怎么做,如果有人知道请帮助我实现这一目标。

Thank You.谢谢你。

You can try using axios library and send http POST request like this您可以尝试使用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);
  });

Official Doc: https://axios-http.com/docs/post_example官方文档: https://axios-http.com/docs/post_example

You can add axios library using npm install axios command.您可以使用npm install axios命令添加 axios 库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM