mvc登录功能实现
asp mvc登录功能实现
Q1: 使用MVC实现登录功能
首先,从底层开始即Models:
(1)通用数据访问类(封装数据访问类方法):SqlHelper类
使用命名空间:using System.Data;
using System.Data.SqlClient;
using System.Configuration;//使用配置文件Web.config所需的命名空间
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace mvcDemo.Models
{
///
/// (1)通用访问类(封装数据访问类方法)
///
public class SqlHelper
{
//定义链接字符串
private static string connString = ConfigurationManager.ConnectionStrings["connString"].ToString();//使用配置文件
public static SqlDataReader GetReader(string sql)
{
SqlConnection con = new SqlConnection(connString);
SqlCommand com = new SqlCommand(sql, con);
try
{
con.Open();
return com.ExecuteReader(CommandBehavior.CloseConnection);//dataReader关闭后自动关闭
}
catch (Exception ex)
{
//写出错误日志
throw ex;
}
}
}
}
web.config:配置为
(2)数据访问类:实体名称+Service,需使用命名空间:
using System.Data;
using System.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace mvcDemo.Models
{
///
///(2) 数据访问类
///
public class sysAdminService
{///
/// 根据账号和密码登录
///
///
///
public sysAdmin AdminLogin(sysAdmin objAdmin)//返回对象思考??及对参数为实体的思考??
{
string sql = "select LoginName from First where LoginId={0}and LoginPwd='{1}'";
sql = string.Format(sql,objAdmin.LoginId,objAdmin.Loginpwd);//格式化
SqlDataReader objReader = SqlHelper.GetReader(sql);
if (objReader.Read())
{
objAdmin.LoginName = objReader["LoginName"].ToString();
}
else
{
objAdmin = null;
}
objReader.Close();
return objAdmin;
}
}
}
(3)实体类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace mvcDemo.Models
{
///
/// 实体类
///
public class sysAdmin
{
public int LoginId { get; set; }
public string LoginName { get; set; }
public string Loginpwd { get; set; }
}
}
其次,Views()【视图层】使用form提交
@{
Layout = null;
}
<meta name="viewport" content="width=device-width" />
<body>
用户名:
密码: