MVC笔记——内含数据库设计、Cookie、Session等(三)

1. 工具类如何写一个增删改的方法

private string connStr = ConfigurationManager.AppSettings["connString"];

        /// <summary>
        /// 增删改
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public bool ExcuteSql(string sql,SqlParameter[] parameters)
        {
            bool result = false;
            SqlConnection connection = null;
            try
            {
                connection = new SqlConnection(connStr);
                connection.Open();
                SqlCommand sqlCommand = new SqlCommand(sql, connection);
                sqlCommand.Parameters.AddRange(parameters);
                int sum = sqlCommand.ExecuteNonQuery();
                result = sum > 0;
                return result;
            }
            catch (Exception ex)
            {
                return result;
            }
            finally
            {
                connection.Close();
            }
        }

2. 如何写向表里面插入一条记录的sql

假设有一个 UserInfo 表,里面有 UserName和UserPwd 两个字段

insert into dbo.UserInfo(UserName,UserPwd)
values('轰焦冻','1234');

3. 怎么查询一张表的记录

假设有一个 UserInfo 表

select * from dbo.UserInfo

4. Ajax的提交格式

$.ajax({
   type: "POST",
   url: url,
   data: data,
   success: success,
   dataType: dataType
 });

5. 工具类如何写一个查询的方法

        /// <summary>
        /// 查询一条
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public int ExecuteScalar(string sql, SqlParameter[] parameters)
        { 
            SqlConnection connection = null;
            int sum = -1;
            try
            {
                //创建连接
                connection = new SqlConnection(connStr);
                //打开连接
                connection.Open();
                //准备预处理
                SqlCommand sqlCommand = new SqlCommand(sql, connection);
                sqlCommand.Parameters.AddRange(parameters);
                //处理返回结果
                object result = sqlCommand.ExecuteScalar();
                sum = Convert.ToInt32(result);
                return sum;
            }
            catch (Exception ex)
            {
                return sum;
            }
            finally
            {
                connection.Close();
            }
        }

6. 如何引入第三方类库

  • 创建项目Remote用来调用第三方提供的类
  • 执行“引用”右键点击“管理NuGit程序包”,随后在“浏览”中添加第三方的引用类库
  • 最后封装相对应的属性

7. WebConfig如何配置变量的值? 后台如何读取

 

在Web.config中的appSettings中配置变量的值,如下面代码所示

<appSettings>
    <add key="appId" value="1400235815"/>
    <add key="appKey" value="2d316373a804c33fbf0d4b269bbaf0ea"/>
</appSettings>

 

后台通过ConfigurationManager.AppSettings["appId"](或["appKey"])进行读取
 

8. 工具类如何写一个数据集的方法

private string connStr = ConfigurationManager.AppSettings["connString"];
		
	/// <summary>
        /// 查询
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static DataSet Query(string sql, SqlParameter[] parameters)
        {
            SqlConnection connection = null;
            //数据集
            DataSet dataSet = new DataSet();
            try
            {
                //创建连接
                connection = new SqlConnection(connStr);
                //打开连接
                connection.Open();
                //准备预处理
                SqlCommand sqlCommand = new SqlCommand(sql, connection);
                if (parameters!=null)
                {
                    sqlCommand.Parameters.AddRange(parameters);
                }

                //适配器
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
                //装载数据集
                sqlDataAdapter.Fill(dataSet);

                return dataSet;
            }
            catch (Exception ex)
            {
                return dataSet;
            }
            finally
            {
                connection.Close();
            }
        }

 9. 数据集如何转换成List<T> [知识点:反射]

        /// <summary>
        /// 将一个datatable 转换成List集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> DataTableToList<T>(DataTable dt)
        {
            List<T> result = new List<T>();
            for (int i = 0;i<dt.Rows.Count;i++)
            {
                //将T反射
                T type = Activator.CreateInstance<T>();
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    //获取当前 type 的所有集合
                    PropertyInfo[] propertyInfo = type.GetType().GetProperties();
                    //遍历属性
                    foreach (PropertyInfo info in propertyInfo)
                    {
                        //如果当前列名等于当前属性的名称
                        if (dt.Columns[j].ColumnName == info.Name)
                        {
                            //给当前的属性赋值
                            if (dt.Rows[i][j] != DBNull.Value)
                            {
                                info.SetValue(type, dt.Rows[i][j]);
                            }
                            else
                            {
                                info.SetValue(type, null);
                            }
                        }
                    }
                }
                result.Add(type);
            }
            return result;
        }

10. 什么Cookie?什么是Session? 两者有什么区别

  • cookie 是一种发送到客户浏览器的文本串句柄,并保存在客户机硬盘上,可以用来在某个WEB站点会话间持久的保持数据。
  • session 指的就是访问者从到达某个特定主页到离开为止的那段时间。
  • cookie和session都是用来跟踪浏览器用户身份的会话方式
  • cookie 和session的区别是:cookie数据保存在客户端,session数据保存在服务器端
     

11. Cookie和Session的使用方式

 cookie的用法

//赋值:
    HttpCookie cookie  =new HttpCookie("tempMsg");
    cookie.Values["Email"] = "soaeon@163.com";
    cookie.Values["key"] = "soaeon" ;
    cookie.Domain = "soaeon.com";   //设置当前cookie所属于的域
    cookie.Expires = (DateTime)expiresTime   //设置cookie的过期时间(持久cookie)
    System.Web.HttpContext.Current.Response.Cookies.Set(cookie);

//取值:
    HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies["tempMsg"];
    string email = cookie.Values["Email"]; 
    string key = cookie.Values["key"];

 session的用法
 

//赋值
    Session["name"] = "soaeon@163.com";

//取值      
    if (Session["name"] != null)
    {
        string str = Session["name"].ToString();
    }

12. 什么是路由?如何配置路由

路由就是一个路径的解析,根据客户端提交的路径,将请求解析到相应的控制器上; 
从 URL 找到处理这个 URL 的类和函数。

配置路由时
项目下的Contorls文件夹下的ValuesController会出现一些方法,但webapi请求语法并不是那么的好用,所以我们先修改路由规则,使其更符合我们平常使用MVC的设计习惯:
(1) 将routeTemplate: "api/{controller}/{id}",修改为routeTemplate: "api/{controller}/{action}/{id}",
(2) 之后你就发现我们也需要传方法名称才可以到指定的方法
以上是如何修改全局路由,那么修改完后我们在get请求的要这样使用(其中model模型自己创建哦)
 

(1) 方法



//1、 Get 方法的参数。http://程序ip:程序端口/api/values/Login?phoneNum=123&password=123
        [HttpGet]
        public string Login(string phoneNum, string password)
        {
            return string.Format("phoneNum:{0},password:{1}", phoneNum, password);
        }
        //这样写就行
        //如果用模型对象,则必须标注[FromUri],http://程序ip:程序端口/api/values/Login?phoneNum=123&password=123
        [HttpGet]
        public bool Login2([FromUri]LoginModel model)
        {
            if (model.phoneNum =="123" && model.password == "123")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

(2)model对象

public class LoginModel
{
    public string userName { get; set; }
    public string phoneNum { get; set; }
    public string password { get; set; }
}

 

 

13. 控制器的方法如何返回一个Json对象

方法返回类型改为 JsonResult
return Json(对象名)

14. Ajax如何接受Json对象并做判断

 

    success: function (data) {
                 if (data.Success) {
                        alert("注册成功");                                
                        window.location.href = "../Login/Login";
                  } else {
                        alert("注册失败");                           
                        window.location.href = "../Login/Register";
                  }
             }

15. Ajax提交,Form表单需要注意什么问题

<from>表单提交的时候要删掉
原理——submit类型的按钮提交会把错误信息提交到后台

16. Sql语句参数化处理

        public bool AddUserInfo(UserInfo userInfo)
        {
            bool result = false;
            string sql = "insert into dbo.UserInfo(UserName,UserPwd)" +
                $"values(@UserName,@UserPwd)";
            SqlHelper sqlHelper = new SqlHelper();

            
            SqlParameter[] parameters =
            {
                new SqlParameter()
                {
                    DbType = System.Data.DbType.String,
                    ParameterName ="@UserName",
                    Value = userInfo.UserName
                },
                new SqlParameter()
                {
                    DbType = System.Data.DbType.String,
                    ParameterName ="@UserPwd",
                    Value = userInfo.UserPwd
                },
            };
            result = sqlHelper.ExcuteSql(sql,parameters);
            return result;
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值