简体   繁体   中英

Validate login form ASP.NET MVC

so I am trying to make my login form to work. I have one table on my database that I want to be able to log in with. The table has two rows, username and password, and when user types in correctly, it should be redirected to the correct page. But when I press the button, nothing happens, what am I doing wrong here?

Model:

namespace Barndomshem.Models
{
    public class User
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }
}

View:

<div class="container">
    <div class="row">
        <div class="box">
            <div class="col-lg-12">
                <form class="form-wrapper" id="contact-form" method="post" role="form" novalidate>
                    <div class="form-group">
                        <div class="row">
                            <div class="form-group col-lg-4">
                                <label for="name">
                                    Användarnamn
                                </label>
                                <input type="text" id="name" name="name" class="form-control" data-errmsg="Fyll i användarnamn."
                                       placeholder="Ditt Användarnamn" required />
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="row">
                            <div class="form-group col-lg-4">
                                <label for="number">
                                    Lösenord
                                </label>
                                <input type="text" id="number" name="number" class="form-control" data-errmsg="Fyll i lösenord."
                                       placeholder="Ditt Lösenord" />
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-2 col-sm-2 offset2">
                            <input type="submit" value="Skicka" class="btn btn-primary" />
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

Controller:

using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using Barndomshem.Models;


namespace Barndomshem.Controllers
{
    public class RapportController : Controller
    {
        SqlConnection connection = new SqlConnection(@"Data Source=.\SQLExpress;Initial Catalog=Barndomshem;Integrated Security=True");
        SqlCommand command = new SqlCommand();
        SqlDataReader reader;

        public ActionResult Index()
        {
            var user = new User();

            Session["UserName"] = user;

            if (Session["UserName"] == null)
            {
                return RedirectToAction("/Rapport/Validate");
            }

            return View();
        }

        public ActionResult Validate(User user)
        {
            var query = command.CommandText = "SELECT Username FROM User";
            command.CommandType = CommandType.Text;
            command.Connection = connection;

            connection.Open();

            if (user.Username == query)
            {
                return RedirectToAction("/Rapport", user);
            }

            connection.Close();

            return View();
        }
    }
}

You're on the right track but there are a couple of problems with your code, namely:

  • The View is not calling the Validate() action in the controller.
  • Your ADO.NET logic to connect to the database is completely wrong.
  • Your SQL query does not contain a WHERE clause.
  • You're not making use of [AllowAnonymous] and [Authorize] authentication attributes provided by MVC.

You need to make the following changes to your code:

1.Web.config:

1.1Add a <connectionStrings> element in the Web.config (under <configuration> ):

  <connectionStrings>
    <add name="ConnectionString" connectionString="Your connection string"/>
  </connectionStrings> 

1.2Add an <authentication> element in the Web.Config(under <system.web> ):

<authentication mode="Forms">
  <forms loginUrl="~/Login/Index" timeout="2880" />
</authentication>

2.Decorate your HomeController with [Authorize]

[Authorize]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

3.LoginController:

public class LoginController : Controller
{
    [AllowAnonymous]
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Validate(User user)
    {
        try
        {
            string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            using (var connection = new SqlConnection(cs))
            {
                string commandText = "SELECT Username FROM [User] WHERE Username=@Username AND Password = @Password";
                using (var command = new SqlCommand(commandText, connection))
                {
                    command.Parameters.AddWithValue("@Username", user.Username);
                    command.Parameters.AddWithValue("@Password", user.Password);
                    connection.Open();

                    string userName = (string)command.ExecuteScalar();

                    if(!String.IsNullOrEmpty(userName))
                    {
                        System.Web.Security.FormsAuthentication.SetAuthCookie(user.Username, false);
                        return RedirectToAction("Index", "Home");
                    }

                    TempData["Message"] = "Login failed.User name or password supplied doesn't exist.";

                    connection.Close();
                }
            }
        }
        catch(Exception ex)
        {
            TempData["Message"] = "Login failed.Error - " + ex.Message;
        }
        return RedirectToAction("Index");
    }
}

4.Login Index View:

@model Barndomshem.Models.User

@using (Html.BeginForm("Validate", "Login"))
{
    <span>User Name</span> <input required="required" type="text" name="Username" /> <br />
    <span>Password</span> <input required="required" type="password" name="Password" />    <br />
    <input type="submit" value="Login" />
}

@if (TempData["Message"] != null)
{
    <span style="color:red;">@TempData["Message"].ToString()</span>
}

Also read the following article:

MVC forms authentication by Jon Galloway

 private void Button_Click(object sender, EventArgs e)
    {
        String user = txtUser.Text;
        String Password = txtPassword.Text;

        if (user == "admin" & Password == "admin123")
        {
            MessageBox.Show("Login Successfully", "info", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        else if( (user == "" || Password == "") || (user == "" && Password == ""))
        {
            MessageBox.Show("Please Enter User Name and Password!", "info", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }          
        
        else
            MessageBox.Show("Incorrect Username or Password", "alter", MessageBoxButtons.OK, MessageBoxIcon.Error);                   
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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