1、對MVC的認識 1、啟動項在Global.asax.cs文件中,RouteConfig.RegisterRoutes(RouteTable.Routes);定義路由事件,可以設置啟動項; 2、Views/Home/Index.cshtml文件是頁面內容,在@....@中直接寫C#語句。該頁面可以 ...
1、對MVC的認識
1、啟動項在Global.asax.cs文件中,RouteConfig.RegisterRoutes(RouteTable.Routes);定義路由事件,可以設置啟動項【預設是Home/Index】;
2、Views/Home/Index.cshtml文件是頁面內容,在@....@中直接寫C#語句。該頁面可以用easyui進行佈局、控制項樣式模仿等;
2、知識點
2.1、小知識
<iframe src="/NewList/Index" scrolling="no" width="100%" height="100%" frameborder="0"></iframe> src是iframe中的url
overflow:hidden影藏滾動條
版權符號:“©”
2.2、超鏈接
eg:點擊新聞管理就打開這個頁面
<div title="新聞管理" iconCls="icon-ok" style="overflow:auto;padding:10px;">
<a href="javascript:void(0)" class="detailLink123" url="/NewList/Index">新聞管理</a>
</div>
1 <script type="text/javascript"> 2 $(function () { 3 binClickEvent(); 4 }); 5 function binClickEvent() { 6 //綁定超鏈接的單擊事件 7 $(".detailLink123").click(function () { 8 var title = $(this).text(); 9 var url = $(this).attr("url"); 10 var isExt = $('#tt').tabs('exists', title);//判斷頁簽是否存在 11 if (isExt) { //如果該標簽頁存在,就不增加新的標簽頁了 12 $('#tt').tabs('select', title); 13 return; 14 } 15 16 $('#tt').tabs('add', { 17 title: title, 18 content: showContent(url), 19 closable: true 20 }); 21 22 }); 23 } 24 //頁簽中顯示的內容 25 function showContent(url) { 26 var strHtml = '<iframe src="' + url + '" scrolling="no" width="100%" height="100%" frameborder="0"></iframe>'; 27 return strHtml; 28 } 29 </script>js代碼
2.3、驗證用戶登錄
<script type="text/javascript"> //刷新驗證碼 function changeCheckCode() { //得到img元素,給它的src屬性賦值 $("#img").attr("src",$("#img").attr("src")+1); //第一次id=1,第二次id=2 } //登錄成功後的回調函數 function afterLogin(data) {//data為LoginController中UserLogin方法的返回值 var serverData = data.split(':'); //數據用:來分隔,得到的是數組 if (serverData[0] == "ok") { window.location.href = "/Home/Index"; //成功,跳轉 } else if (serverData[0] == "no") { $("#errorMsg").text(serverData[1]); //失敗,返回錯誤信息,刷新驗證碼 changeCheckCode(); } else { $("#errorMsg").text("系統繁忙!!"); //否則系統繁忙 } } </script> <!--使用ajax非同步,OnSucess是回調函數,當登錄成功後做什麼--> @using (Ajax.BeginForm("UserLogin", new { }, new AjaxOptions() { HttpMethod = "post", OnSuccess = "afterLogin" }, new { id = "loginForm" })) { <table cellpadding="0" cellspacing="0"> <tbody> <tr> <td align="left" colspan="2"> <h3> 請使用傳智播客CMS系統賬號登錄 </h3> </td> </tr> <tr> <td align="right"> 賬號: </td> <td align="left"> <input type="text" name="LoginCode" id="LoginCode" class="login-text" /> </td> </tr> <tr> <td align="right"> 密碼: </td> <td align="left"> <input type="password" name="LoginPwd" id="LoginPwd" value="123" class="login-text" /> </td> </tr> <tr> <td> 驗證碼: </td> <td align="left"> <input type="text" class="login-text" id="code" name="vCode" value="1" /> </td> </tr> <tr> <td></td> <td> <!--這裡加/?id=1,是為了每點擊刷新一次id加1,都是一個新的url,瀏覽器會重新載入觸發這個方法,而不使用緩存--> <img id="img" src="/Login/ShowValidateCode/?id=1" style="float: left; height: 24px;" /> <div style="float: left; margin-left: 5px; margin-top: 10px;"> <a href="javascript:void(0)" onclick="changeCheckCode();return false;">看不清,換一張</a> </div> </td> </tr> <tr> <td align="center" colspan="2"> <input type="submit" id="btnLogin" value="登錄" class="login-btn" /> <span id="errorMsg"></span> </td> </tr> </tbody> </table> }前臺代碼
//Controller類 /// <summary> /// MVC寫一個功能的步驟: /// 1、創建Controller /// 2、添加View /// 3、在Controller中調用BLL,BLL中調用DAL /// </summary> public class LoginController : Controller { //引用BLL、Model、Common層 BLL.UserInfoService userInfoBll = new BLL.UserInfoService(); // GET: Login public ActionResult Index() //指向Login/Index.cshtml文件 { return View(); } public ActionResult UserLogin() { //1、判斷驗證碼是否正確 string code = Session["code"]== null ? string.Empty : Session["code"].ToString(); if (string.IsNullOrEmpty(code)) return Content("no:驗證碼不能為空!"); Session["code"] = null; //清空seesion記錄 string userCode = Request["vCode"]; //得到用戶輸入的驗證碼 if (!userCode.Equals(code, StringComparison.InvariantCultureIgnoreCase)) return Content("no:驗證碼不正確!"); //2、用戶名密碼是否正確,首先在Dal層查詢邏輯,在Bll層中調用Dal層,再Controller中調用Bll層 string userName = Request["LoginCode"]; string userPwd = Request["LoginPwd"]; Model.UserInfo user = userInfoBll.GetUserInfo(userName, userPwd); if (user != null) //該用戶名密碼存在 { Session["UserInfo"] = user; return Content("ok: 用戶登錄成功!"+ user.UserName + user.UserMail); //Content用作返回標識 } else return Content("no: 用戶名密碼不正確!"); } /// <summary> /// ActionResult是一個父類,可以返回很多類型(視圖、圖片...) /// </summary> /// <returns></returns> public ActionResult ShowValidateCode() { Common.ValidateCode ValidateCode = new Common.ValidateCode(); string code = ValidateCode.CreateValidateCode(4); //獲取驗證碼 Session["code"] = code; //把code保存在Session中,以便和用戶輸入的code作比較 byte[] buf = ValidateCode.CreateValidateGraphic(code); //獲取圖片 return File(buf, "image/jpeg"); } } //Bll public UserInfo GetUserInfo(string name, string pwd) { return userInfoDal.GetUserInfo(name, pwd); } //Dal public UserInfo GetUserInfo(string userName, string userPwd) { string sql = "select * from UserInfo where UserName = :userName and UserPwd = :userPwd"; OracleParameter[] pars = { new OracleParameter(":userName", OracleType.NVarChar, 50), new OracleParameter(":userPwd", OracleType.NVarChar,50)}; pars[0].Value = userName; pars[1].Value = userPwd; //調用方法查詢 DataTable dt = SqlHelper.GetTable(sql, CommandType.Text, pars); UserInfo user = null; if(dt.Rows.Count > 0) { user = new UserInfo(); LoadEntity(user, dt.Rows[0]); //載入一行數據 } return user; } private void LoadEntity(UserInfo user, DataRow row) { user.UserId = Convert.ToInt32(row["ID"]); //資料庫中不允許為空的不用判斷 //資料庫中允許為空的,如果為空則給它賦值一個空字元串 user.UserName = row["UserName"] != DBNull.Value ? row["UserName"].ToString() : string.Empty; user.UserPwd = row["UserPwd"] != DBNull.Value ? row["UserPwd"].ToString() : string.Empty; user.UserMail = row["UserMail"] != DBNull.Value ? row["UserMail"].ToString() : string.Empty; user.RegTime = Convert.ToDateTime(row["RegTime"]); }後臺代碼
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.OracleClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CMS.DAL { public class SqlHelper { private static readonly string conStr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString; /// <summary> /// 查詢 /// </summary> /// <param name="sql"></param> /// <param name="type"></param> /// <param name="parms"></param> /// <returns></returns> public static DataTable GetTable(string sql, CommandType type, params OracleParameter[] parms) { using(OracleConnection conn = new OracleConnection(conStr)) { using(OracleDataAdapter adapter = new OracleDataAdapter(sql, conn)) { adapter.SelectCommand.CommandType = type;//設置數據類型 if (parms != null) adapter.SelectCommand.Parameters.AddRange(parms); DataTable dt = new DataTable(); adapter.Fill(dt); return dt; } } } /// <summary> /// 增刪改 /// </summary> /// <param name="sql"></param> /// <param name="type"></param> /// <param name="pars"></param> /// <returns>影響的行數</returns> public static int ExecuteNonQuery(string sql, CommandType type, params OracleParameter[] pars) { using(OracleConnection conn = new OracleConnection(conStr)) { using(OracleCommand cmd = new OracleCommand(sql, conn)) { cmd.CommandType = type; if (pars != null) cmd.Parameters.AddRange(pars); conn.Open(); return cmd.ExecuteNonQuery(); } } } /// <summary> /// 返回條數 /// </summary> /// <param name="sql"></param> /// <param name="type"></param> /// <param name="pars"></param> /// <returns></returns> public static int ExecuteScalar(string sql, CommandType type, params OracleParameter[] pars) { using (OracleConnection conn = new OracleConnection(conStr)) { using (OracleCommand cmd = new OracleCommand(sql, conn)) { cmd.CommandType = type; if (pars != null) cmd.Parameters.AddRange(pars); conn.Open(); return Convert.ToInt32(cmd.ExecuteScalar()) ; } } } } }SqlHelper
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace CMS.Common { public class ValidateCode { public ValidateCode() { } /// <summary> /// 驗證碼的最大長度 /// </summary> public int MaxLength { get { return 10; } } /// <summary> /// 驗證碼的最小長度 /// </summary> public int MinLength { get { return 1; } } /// <summary> /// 生成驗證碼 /// </summary> /// <param name="length">指定驗證碼的長度</param> /// <returns></returns> public string CreateValidateCode(int length) { int[] randMembers = new int[length]; int[] validateNums = new int[length]; string validateNumberStr = ""; //生成起始序列值 int seekSeek = unchecked((int)DateTime.Now.Ticks); Random seekRand = new Random(seekSeek); int beginSeek = (int)seekRand.Next(0, Int32.MaxValue - length * 10000); int[] seeks = new int[length]; for (int i = 0; i < length; i++) { beginSeek += 10000; seeks[i] = beginSeek; } //生成隨機數字 for (int i = 0; i < length; i++) { Random rand = new Random(seeks[i]); int pownum = 1 * (int)Math.Pow(10, length); randMembers[i] = rand.Next(pownum, Int32.MaxValue); } //抽取隨機數字 for (int i = 0; i < length; i++) { string numStr = randMembers[i].ToString(); int numLength = numStr.Length; Random rand = new Random(); int numPosition = rand.Next(0, numLength - 1); validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1)); } //生成驗證碼 for (int i = 0; i < length; i++) { validateNumberStr += validateNums[i].ToString(); } return validateNumberStr; } /// <summary> /// 創建驗證碼的圖片 /// </summary> /// <param name="context">要輸出到的page對象</param> /// <param name="validateNum">驗證碼</param> public void CreateValidateGraphic(string validateCode, HttpContext context) { Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22); Graphics g = Graphics.FromImage(image); try { //生成隨機生成器 Random random = new Random(); //清空圖片背景色 g.Clear(Color.White); //畫圖片的干擾線 for (int i = 0; i < 25; i++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic)); LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true); g.DrawString(validateCode, font, brush, 3, 2); //畫圖片的前景干擾點 for (int i = 0; i < 100; i++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next())); } //畫圖片的邊框線 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); //保存圖片數據 MemoryStream stream = new MemoryStream(); image.Save(stream, ImageFormat.Jpeg); //輸出圖片流 context.Response.Clear(); context.Response.ContentType = "image/jpeg"; context.Response.BinaryWrite(stream.ToArray()); } finally { g.Dispose(); image.Dispose(); } } /// <summary> /// 得到驗證碼圖片的長度 /// </summary> /// <param name="validateNumLength">驗證碼的長度</param> /// <returns></returns> public static int GetImageWidth(int validateNumLength) { return (int)(validateNumLength * 12.0); } /// <summary> /// 得到驗證碼的高度 /// </summary> /// <returns></returns> public static double GetImageHeight() { return 22.5; } //C# MVC 升級版 /// <summary> /// 創建驗證碼的圖片 /// </summary> /// <param name="containsPage">要輸出到的page對象</param> /// <param name="validateNum">驗證碼</param> public byte[] CreateValidateGraphic(string validateCode) { Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22); Graphics g = Graphics.FromImage(image); try { //生成隨機生成器 Random random = new Random(); //清空圖片背景色 g.Clear(Color.White); //畫圖片的干擾線 for (int i = 0; i < 25; i++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic)); LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true); g.DrawString(validateCode, font, brush, 3, 2