新手求助:将ASP.NET登录页转换为ASP.NET MVC+React.js实现
Hey there! Since you're new to React.js and working on converting your old ASP.NET Web Forms Login.aspx to an ASP.NET MVC + React setup, let me break this down into simple, actionable steps for you.
First, let's recap the core part of your original Login.aspx that we're replicating: two input groups for username (personal number) and password, with Material Icons as add-ons.
First, we'll create an AccountController to handle login requests. This replaces the code-behind logic from your Web Forms page.
public class AccountController : Controller { // GET request to load the login page public ActionResult Login() { return View(); } // POST request to handle login validation [HttpPost] public JsonResult Login(string userName, string password) { // Replace this with your actual user validation logic (e.g., check database) bool isUserValid = ValidateCredentials(userName, password); if (isUserValid) { // Handle successful login (e.g., set authentication cookie/session) return Json(new { success = true, message = "Login successful!" }); } else { return Json(new { success = false, message = "Invalid personal number or password" }); } } private bool ValidateCredentials(string userName, string password) { // Temporary hardcoded check - replace with your real logic return userName == "123456" && password == "securepass"; } }
Next, we'll create a React component that mirrors the UI from your original Login.aspx, plus adds form handling logic. We'll use functional components and React Hooks since they're simpler for beginners.
Create a Login.jsx file in your React project:
import { useState } from 'react'; const Login = () => { // State to hold form input values const [formData, setFormData] = useState({ userName: '', password: '' }); // State to show login status messages const [loginMessage, setLoginMessage] = useState(''); // Update form state when inputs change const handleInputChange = (e) => { const { name, value } = e.target; setFormData(prevState => ({ ...prevState, [name]: value })); }; // Handle form submission const handleSubmit = async (e) => { e.preventDefault(); setLoginMessage(''); try { // Send login request to MVC backend const response = await fetch('/Account/Login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formData) }); const result = await response.json(); if (result.success) { setLoginMessage(result.message); // Redirect to your home page after successful login window.location.href = '/Home/Index'; } else { setLoginMessage(result.message); } } catch (error) { setLoginMessage('Oops! Something went wrong during login.'); console.error('Login error:', error); } }; return ( <div className="content"> <form onSubmit={handleSubmit}> {/* Username Input Group */} <div className="input-group mb-3"> <span className="input-group-addon"> <i className="material-icons">account_circle</i> </span> <input type="text" name="userName" className="form-control" placeholder="Personal Number..." value={formData.userName} onChange={handleInputChange} required /> </div> {/* Password Input Group */} <div className="input-group mb-3"> <span className="input-group-addon"> <i className="material-icons">lock</i> </span> <input type="password" name="password" className="form-control" placeholder="Password..." value={formData.password} onChange={handleInputChange} required /> </div> {/* Login Button */} <button type="submit" className="btn btn-primary w-100">Login</button> {/* Status Message */} {loginMessage && <p className="mt-3 text-center">{loginMessage}</p>} </form> </div> ); }; export default Login;
Now we need to render the React component in an MVC view. First, bundle your React component (using Webpack, Vite, or Create React App's build tool) and place the bundle file in your MVC project's wwwroot/dist folder.
Then create a Login.cshtml view in the /Views/Account folder:
@{ ViewBag.Title = "Login"; } <!-- Container where React will mount the component --> <div id="login-root"></div> <!-- Load your bundled React script --> <script src="~/dist/login.bundle.js"></script>
Add this code to your React entry file (e.g., index.js) to mount the component:
import React from 'react'; import ReactDOM from 'react-dom/client'; import Login from './Login'; const root = ReactDOM.createRoot(document.getElementById('login-root')); root.render(<Login />);
- Material Icons: Make sure you've added Material Icons to your project locally (avoid external links if preferred) by including the icon font files in your
wwwrootand referencing them in your Layout's CSS. - Form Validation: You can add more robust front-end validation (e.g., minimum length for personal number) using libraries like
react-hook-formif you want, but the basic setup above works for starters. - Security: Don't forget to add anti-forgery tokens to your MVC POST action (use
@Html.AntiForgeryToken()in the view and validate it in the controller) to prevent CSRF attacks. - Axios Alternative: If you find
fetcha bit clunky, you can use theaxioslibrary for HTTP requests—it's more intuitive for beginners.
内容的提问来源于stack exchange,提问作者Mohan

