asp.MCV如何将字符串转换为布尔标志
本文关键字:转换 布尔 标志 字符串 MCV asp | 更新日期: 2023-09-27 18:15:34
我正在尝试做一个登录页面。但是当我按F5页面这一行给出了一个错误:
flag = Convert.ToBoolean(cmd.ExecuteScalar());
Login.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace LoginFormApp.Models
{
public class Login
{
[Required(ErrorMessage = "Username is required")]
[Display(Name = "Username")]
public string username { get; set; }
[Required(ErrorMessage = "Password is required")]
[Display(Name = "Password")]
public string password { get; set; }
public bool checkUser(string username, string password)
{
bool flag = false;
string connString = ConfigurationManager.ConnectionStrings["MyDatabaseEntities"].ConnectionString ;
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("Select count(*) from Login where username='" + username + "' and password='" + password + "'", conn);
flag = Convert.ToBoolean(cmd.ExecuteScalar());
return flag;
}
}
}
}
Index.cshtml
@model LoginFormApp.Models.Login
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>DNDB Login</title>
</head>
<body>
<div style="margin:0 auto; text-align: center; border: 2px; border-style: solid; width:400px;background-color:lightgrey">
@using (Html.BeginForm())
{
<table>
<tr>
<td>@Html.LabelFor(m => m.username)</td>
<td>@Html.TextBoxFor(m => m.username)</td>
<td>@Html.ValidationMessageFor(m => m.username)</td>
</tr>
<tr>
<td>@Html.LabelFor(m => m.password)</td>
<td>@Html.PasswordFor(m => m.password)</td>
<td>@Html.ValidationMessageFor(m => m.password)</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
<tr>
<td></td>
<td>
@ViewBag.Message
</td>
</tr>
</table>
}
</div>
</body>
</html>
show.cshtml
@model LoginFormApp.Models.Login
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Show</title>
</head>
<body>
<div>
<h3> Hi! @Model.username</h3>
</div>
</body>
</html>
Homecontroller.cs
using LoginFormApp.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace LoginFormApp.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ViewResult Index(Login login)
{
if (ModelState.IsValid)
{
if (login.checkUser(login.username, login.password))
{
return View("Show", login);
}
else
{
ViewBag.Message = "Invalid Username or Password";
return View();
}
}
else
{
return View();
}
}
}
}
你做错了,ExecuteScalar()总是返回第一列的值,所以在您的情况下,它返回总数,不能直接转换为布尔值。
int totalCount = Convert.ToInt32(cmd.ExecuteScalar());
flag = totalCount > 0;
可以使用
flag = (int)cmd.ExecuteScalar() == 1;