初入碼田--ASP.NET MVC4 Web應用之創建一個空白的MVC應用程序
初入碼田--ASP.NET MVC4 Web應用開發之二 實現簡單的增刪改查
一、創建T4模板,建立與SQL Sever數據庫的連接(有兩種形式:我們后面使用方法1)
右鍵【Models】-->添加-->新建項-->選擇數據-->ADO.NET實體數據模型
此處有兩個選擇:1、基於已有的SQL Sever數據庫生成。2、先建立數據庫模型,然后根據所建立的模型生成所需的數據庫。
1、選擇從數據庫生成
下一步
新建連接-->服務器名.(.表示主機)-->選擇或輸入數據庫名稱Ddup
下一步(勾選所需添加到模型中的數據庫表)
點擊【完成】,T4模板根據數據庫生成對應的實體模型
2、選擇空模型(EF Code First)
在空白處右鍵-->選擇新增-->實體
實體名稱T001Admin對應生成的數據庫表名T001Admin;實體集默認的是T001AdminSet,將其改為與實體名稱一致;鍵屬性為該實體的主鍵(Code First會在數據庫中默認將該主鍵Id設置為自增長)
這樣我們就創建好了一個帶有自增主鍵Id的表T001Admin
現在來創建T001Admin實體的其他屬性。
右鍵【屬性】-->新增-->標量屬性;然后修改其名稱為:Account。
右鍵【Account】-->屬性,設置Account的屬性
以此類推,創建了T001Admin表和T002AdminGroup表
建立主外鍵關聯:菜單欄選擇【視圖】-->工具箱,點擊【關聯】
點擊T001Admin表的【Id】-->再點擊T002AdminGroup表的fk_T001Admin,這樣主外鍵關聯就建立好了
然后,在編輯區右鍵-->根據模型生成數據庫(在此之前,得先在SQL Sever中新建一個數據庫:Ddup)
新建連接-->服務器名.(.表示主機)-->選擇或輸入數據庫名稱(選擇此前已經創建好的數據庫Ddup)
確定-->下一步,此處是T4模板根據所建立的模型,將其轉換成sql語句,存儲在Models下的Model1.edmx.sql文件的
點擊【完成】,這樣就生成了對應的sql文件
點擊左上角的,Server name為.
點擊【Connect】,消息中顯示已成功完成命令,那么在Ddup數據庫中就已經成功生成了我們之前所建立的實體模型所對應的數據庫表
注意點:此處的Model1Container為我們之后創建EF上下文容器的名稱
我們可以在此Web.config中重新命名,將name=“Model1Container”修改為name=“DBEntities”
<connectionStrings> <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Ddup-20160724074025;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-Ddup-20160724074025.mdf" /> <add name="Model1Container" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=Ddup;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /> </connectionStrings>
然后在Model1.Context.cs中將Model1Container都修改為DBEntities
修改前:
public partial class Model1Container : DbContext { public Model1Container() : base("name=Model1Container") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { throw new UnintentionalCodeFirstException(); } public DbSet<T001Admin> T001Admin { get; set; } public DbSet<T002AdminGroup> T002AdminGroup { get; set; } }
修改后:
public partial class DBEntities : DbContext { public DBEntities() : base("name=DBEntities") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { throw new UnintentionalCodeFirstException(); } public DbSet<T001Admin> T001Admin { get; set; } public DbSet<T002AdminGroup> T002AdminGroup { get; set; } }
三、創建第一個Model--M001LoginDemo.cs
右鍵【Models】-->添加-->類(M001LoginDemo.cs)
DdupEntities為之前配置的web.config中的實體連接名稱
using Ddup.Models.ViewModel; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Ddup.Models { /// <summary> /// 登錄模型演示 /// </summary> public class M001LoginDemo { #region 1.0:判斷能否登錄方法一(個人不推薦) /// <summary> /// 1、定義的一個返回類型為 Boolean 型的方法 /// 2、將來在Controller中接收true or false來判斷是否允許登錄 /// </summary> /// <param name="username"></param> /// <param name="pwd"></param> /// <returns>true or false</returns> public static Boolean LoginDemo1(string account, string pwd) { //初始化EF上下文容器 DdupEntities db = new DdupEntities(); //m => m.Account此為lambda表達式 //db.T001Admin.FirstOrDefault(m => m.Account == account && m.Password == pwd);返回類型為T001Admin,所以定義強類型T001Admin來接收 //T001Admin model = db.T001Admin.FirstOrDefault(m => m.Account == account && m.Password == pwd); //var 可以很智能的識別所需接收的強類型並轉換成它 var model = db.T001Admin.FirstOrDefault(m => m.Account == account && m.Password == pwd); if (model == null) { return false; } else { return true; } } #endregion #region 判斷登錄方法二 /// <summary> /// 1、定義的一個返回類型為 T001Admin 型的方法 /// 2、將來在Controller中接收 是否為null 來判斷是否允許登錄 /// </summary> /// <param name="account"></param> /// <param name="pwd"></param> /// <returns></returns> public static T001Admin LoginDemo2(string account, string pwd) { //初始化EF上下文容器 DdupEntities db = new DdupEntities(); return db.T001Admin.FirstOrDefault(m => m.Account == account && m.Password == pwd); } #endregion #region 判斷登錄方法三(推薦) /// <summary> /// 1、定義的一個返回類型為 T001Admin 型的方法 /// 2、將來在Controller中接收 是否為null 來判斷是否允許登錄 /// 3、此處用模型(Vm001登錄視圖模型)做為參數類型,此前需在Models下 /// 添加新建文件夾ViewModel,然后在ViewModel下創建 Vm001登錄視圖模型.cs, /// 最后需要導入命名空間,在開頭添加 using Ddup.Models.ViewModel; /// </summary> /// <param name="account"></param> /// <param name="pwd"></param> /// <returns></returns> public static T001Admin LoginDemo3(Vm001登錄視圖模型 model) { //初始化EF上下文容器 DdupEntities db = new DdupEntities(); return db.T001Admin.FirstOrDefault(m => m.Account == model.account && m.Password == model.pwd); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Ddup.Models.ViewModel { public class Vm001登錄視圖模型 { public string account { get; set; } public string pwd { get; set; } public string Vcode { get; set; } } }
四、創建一個Controller--C01LoginController.cs(我們在這里選擇--MVC 5控制器-空)
右鍵【Controllers】-->添加-->控制器
using Ddup.Models; using Ddup.Models.ViewModel; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Ddup.Controllers { public class C01LoginController : Controller {public ActionResult Login() { return View(); } [HttpPost] public ActionResult Login(Vm001登錄視圖模型 model) { try { if (ModelState.IsValid) { #region 1.0:登錄演示方法一 //var userinfo1 = M001LoginDemo.LoginDemo1(model.account, model.pwd); //if (userinfo1 == true) //{ // RedirectToAction("Index","Home"); //} #endregion #region 2.0:登錄演示方法二 //var userinfo2 = M001LoginDemo.LoginDemo2(model.account, model.pwd); //if (userinfo2 != null) //{ // RedirectToAction("Index","Home"); //} #endregion #region 3.0:登錄演示方法3 var userinfo3 = M001LoginDemo.LoginDemo3(model); if (userinfo3 != null) { RedirectToAction("Index","Home"); } #endregion } } catch (Exception ex) { ModelState.AddModelError("", ex.Message); } return View("Error"); } } }
五、創建一個登錄視圖Login.cshtml
右鍵【Login】創建登錄視圖
@model Ddup.Models.ViewModel.Vm001登錄視圖模型 @{ ViewBag.Title = "Login"; } @using(Html.BeginForm()) { @Html.ValidationSummary(true) <div class="form-group" style="height:40px;margin-top:50px"> <div class="row"> @Html.LabelFor(m => m.account, new { @class = "col-md-5 control-label", @style = "text-align:right", @for = "account" }) <div class=" col-md-7"> @Html.TextBoxFor(m => m.account, new { @class = "form-control", placeholder = "請輸入用戶名", @style = "width:240px;", id = "account" }) @Html.ValidationMessageFor(m => m.account) </div> </div> </div> <div class="form-group" style="height:40px;"> <div class="row"> @Html.LabelFor(m => m.pwd, new { @class = "col-md-5 control-label", @style = "text-align:right", @for = "pwd" }) <div class=" col-md-7"> @Html.PasswordFor(m => m.pwd, new { @class = "form-control", placeholder = "請輸入密碼", @style = "width:240px;", id = "pwd" }) @Html.ValidationMessageFor(m => m.pwd) </div> </div> </div> <div class="form-group"> <div class="col-md-5"></div> <div class="col-md-2 col-xs-4"> <input type="submit" value=" 登錄" class="btn btn-default" /> </div> <div class="col-md-5 col-xs-8"> <input type="reset" value=" 重置" class="btn btn-default" /> </div> </div> }
六、創建驗證碼
在C01LoginController.cs控制器下創建,代碼如下:
#region 驗證碼 public MemoryStream Get_Images(int fontSize, int charNumber, string backgroundColor) { //把字符轉換為圖像,並且保存到內存流 //這個數字在調用頁面需要,你要自己算出明確值,注意!注意!注意! var imageW = Convert.ToInt32(fontSize * 1.3) + fontSize * charNumber; //這個數字在調用頁面需要,你要自己算出明確值,注意!注意!注意! var imageH = Convert.ToInt32(2.5 * fontSize); //封裝GDI+位圖 //封裝GDI+繪圖面 var colorBack = ColorTranslator.FromHtml(backgroundColor); //背景顏色 //注意!注意! 確定背景大小 var tempBitmap = new Bitmap(imageW, imageH, PixelFormat.Format32bppRgb); //注意!注意! 繪制背景 var tempGraphics = Graphics.FromImage(tempBitmap); tempGraphics.FillRectangle(new SolidBrush(colorBack), new Rectangle(0, 0, imageW, 5 * imageH)); //為了進行驗證比較 var ran = new Random(); var codeint = ran.Next(1000, 9999); var Vcode = Convert.ToString(codeint); //將結果放入session中 Session["Vcode"] = Vcode; tempGraphics.DrawString(Vcode, new Font("Arial", 16), new SolidBrush(Color.Black), 0, 0); //背景透明 tempBitmap.MakeTransparent(colorBack); var tempStream = new MemoryStream(); tempBitmap.Save(tempStream, ImageFormat.Png); //釋放資源 tempGraphics.Dispose(); //釋放資源 tempBitmap.Dispose(); //關閉打開的流文件 tempStream.Close(); //返回流 return tempStream; } /// <summary> /// 驗證圖片 /// </summary> /// <returns></returns> public FileContentResult GetImage() { var myStream = Get_Images(12, 4, "#ffffff"); return File(myStream.GetBuffer(), "image/Png"); } [HttpPost] public JsonResult CheckValidationCode(string Vcode) { try { return Json(Vcode == Session["Vcode"].ToString()); } catch (Exception) { return Json(false); throw; } } #endregion
注意點:1、需要在Vm001登錄視圖模型中添加一個字段,完成代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; //使用Remote所需程序集 using System.Web.Mvc; namespace Ddup.Models.ViewModel { public class Vm001登錄視圖模型 { public string account { get; set; } public string pwd { get; set; } [Remote("CheckValidationCode", "C01Login", ErrorMessage = "驗證碼錯誤", HttpMethod = "POST")] public string Vcode { get; set; } } }
2、需要在母版頁(~/Views/Shared/_Layout.cshtml)中導入Validate腳本和Validate的非侵入式腳本(如果沒有可以在nutget中下載)
jquery.validate.js,
jquery.validate.unobtrusive.js
最后,我們只需在Login視圖中添加
<div class=" form-group"> @Html.LabelFor(m => m.Vcode, new { @class = "col-md-5 control-label", @style = "text-align:right;", @for = "Vcode" }) <div class="col-md-2"> @Html.TextBoxFor(m => m.Vcode, new { @class = "form-control col-xs-2", placeholder = "驗證碼", @style = "width:80px;", id = "Vcode" }) </div> <div> <img src="~/C01Login/GetImage" alt="驗證碼" id="vcodeimg" style="cursor:pointer;" /> @Html.ValidationMessageFor(m => m.Vcode) </div> </div>
這樣我們的驗證碼功能就實現了O(∩_∩)O哈哈~
本人屬於初學者,如果有何不足,還請見諒,也希望大家多多給意見,謝謝!!!
=================================================================================================
作者:程程程
出處:http://rcddup.cnblogs.com
本文由程程程原創,並發布到博客園,歡迎轉載,但必須在文章頁面明顯位置寫明作者和出處,非常感謝!