VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • C#教程之Asp.net MVC企业管理系统

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>
复制代码

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()) ;
                }
            }
        }
    }
}
复制代码
复制代码
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);
                //画图片的前景干扰点
                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);
                //输出图片流
                return stream.ToArray();
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
    }
}
复制代码


相关教程