Asp.net MVC企業管理系統

来源:https://www.cnblogs.com/SmileSunday/archive/2018/01/30/8383457.html
-Advertisement-
Play Games

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影藏滾動條

   版權符號:“&copy;”

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
              
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1。藍圖 要用藍圖管理項目,需要導入的包是:from flask import Buleprint 具體大致分為三步: 1.先在子模塊中導入藍圖包,然後再創建藍圖對象。 2.然後將子模塊中的視圖函數存儲在藍圖對象中。 3.最後在主模塊的文件夾里註冊藍圖。 下麵分別展示以上三步在項目中的具體操作: 第 ...
  • 1 載入matplotli的繪圖模塊,並重命名為pltimport matplotlib.pyplot as plt2 折線圖import matplotlib.pyplot as pltimport numpy as npx = np.arange(9)y = np.sin(x)z = np.co... ...
  • ———————————————————————————————————————————————————————————————————————————————————————— 本篇開始進行真槍實彈的調試,本文的最後會附上完整的源碼包,方便各位在自己的機器上演練。 如果安裝了 Windows Dri ...
  • 前言 前面學會了單機, 學會了集群, 但是redis咋用啊? 或者說, redis支持哪些數據類型呢? 常用的有五種: String , Hash, List, Set, zset(SortedSet) 一、String String 類型, 在前面也是使用過的. 直接來看一下 可以使用del na ...
  • 前言 redis數據存儲在記憶體中, 就會受到記憶體的限制, 大家都知道, 一臺電腦, 硬碟可以有1T, 但是記憶體, 沒有聽說有1T的記憶體吧. 那如果數據非常多, 超過一臺電腦的記憶體空間, 怎麼辦呢? 正常思維, 都是, 一臺電腦不夠, 那我再加一臺電腦嘛, 不就夠了. redis集群架構圖 每一臺re ...
  • 先來張圖: 這是一張shiro的功能圖: Authentication: 身份認證/登錄,驗證用戶是否擁有相應的身份 Authorization: 授權/許可權驗證,驗證某個已認證的用戶是否擁有某個許可權,包括驗證用戶是否擁有某個角色,或擁有某個操作許可權 Session Management: 會話管理 ...
  • java集合類存放於java.util包中,集合類存放的都是對象的引用,而非對象本身,出於表達上的便利,我們稱集合中的對象就是指集合中對象的引用,集合類型主要有3種:set(集)、list(列表)和map(映射)。 Java API中所用的集合類,都是實現了Collection介面,它的一個類繼承結 ...
  • 1 數組對象創建數組import numpy as npa = np.arange(10)b = np.arange(2,10,1) #[2,10)步長為1c = np.linspace(0,10,20) #[0,10]共20個d = np.array([range(5)]) #用list/tupl... ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...