1.一次請求過來與數據庫交互一次。每次操作表都using() 性能差(可以隨時釋放)
2.N 次操作共用一個DbContext 性能可想而知
3.Web:一個請求共用一個上下文實例
4.WinForm:用using()
實例:
public static MyDbContext GetCurrentDbContext()
{
MyDbContext dbcontext = HttpContext.Current.Items["MyDbContext"] as MyDbContext;
//當前Http上下文不存在當前對象
if (dbcontext == null)
{
dbcontext = new MyDbContext();
HttpContext.Current.Items.Add("", dbcontext);
}
return dbcontext;
}
調用:
protected void Page_Load(object sender, EventArgs e)
{
var dbCotnext = DbContextHelper.GetCurrentDbContext();
}
CallContext 是類似於方法調用的線程本地存儲區的專用集合對象,並提供對每個邏輯執行線程都唯一的數據槽。
數據槽不在其他邏輯線程上的調用上下文之間共享。 當 CallContext 沿執行代碼路徑往返傳播並且由該路徑中的各個對象檢查時,可將對象添加到其中。
//一個線程共用一個上下文實例。一次請求就用一個線程。
MyDbContext dbContext = CallContext.GetData("DbContext") as MyDbContext;
if (dbContext == null)
{
dbContext =new MyDbContext();
CallContext.SetData("DbContext",dbContext);
}
return dbContext;
為什么用EF而不用原生的Ado.Net?
1、極大的提高開發效率:EF是微軟自己的產品,跟VS開發工具集成度比較好,開發中代碼都是強類型的,寫代碼效率非常高,自動化程度非常高,命令式的編程。
2、EF提供的模型設計器非常強大,不僅僅帶來了設計數據庫的革命,也附帶來的自動化生成模型代碼的功能也極大的提高開發和架構設計的效率
3、EF跨數據支持是ORM框架主要功能點之一,帶來的是可以通過僅僅改變配置就可以做到跨數據庫的能力。
4、缺陷:性能差(生成sql腳本階段),在復雜查詢的時候生成的sql腳本效率不是很高。
1、不在數據端額外的消耗性能。
2、根據xml映射關系以及實體的狀態生成相應的sql腳本。
做企業內部管理系統:
進銷存、CRM、HR、OA、ERP、政務系統
MVC和WebFrom的區別:
控制器的作用:
1.接受用戶的請求:表單中獲取數據,從querystring或者Session、Cookie中處理用戶的數據
2.調用業務邏輯層
3.把數據給前台aspx頁面傳遞數據
控制器滿足的約定:
1.以Controller結尾
2.必須非靜態類
3.實現IController接口
Shared所有的控制器都可以去這個文件夾中查找視圖
Action的作用:
1.處理用戶的請求:Request、Response
2.調用業務邏輯
3.把數據傳給View進行展示
偽靜態的寫法:
url: "{controller}/{action}.html",
配置一下屬性:
簡單的用戶注冊:
前台頁面(aspx頁面):
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>UserRegist</title>
</head>
<body>
<div>
<form action="/UserInfo/ProcessUserRegist" method="POST" >
<table>
<tr>
<td>用戶名:</td><td><input type="text" name="txtName"/></td>
</tr>
<tr>
<td>密碼:</td><td><input type="text" name="txtPwd"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交"/>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
控制器的代碼:
public ActionResult re(FormCollection collection)
public ActionResult ProcessUserRegist(string txtName,string txtPwd,ParaClass data)
{
//怎么拿到用戶提交來的表單內容?
//string str = Request["txtName"];
//string str = collection["txtName"];
//Response.Write("ok" + str);
//Response.End();
return Content("ok" + txtName);//往前台輸出一個字符串。等價於 Response.Write() + Response.End()
}
public class ParaClass
{
public string txtName { get; set; }
public string txtPwd { get; set; }
}
HTML.ActionLink方法:
<%= Html.ActionLink("超級鏈接的文本","About","Home",new {demo="sssss",mm="ss33"},new {style="Color:red",id=33,@class="ssssddd"}) %>
下拉列表:
<%= Html.DropDownList("CityList") %>
ViewData["CityList"] = new List<SelectListItem>()
{
new SelectListItem(){Selected = true,Text = "北京",Value ="1"},
new SelectListItem(){Selected = false,Text = "天津",Value ="2"},
new SelectListItem(){Selected = false,Text = "西紅柿",Value ="3"}
};
自定義擴展方法:
namespace System.Web.Mvc//一般情況下把擴展方法所在的命名空間跟要擴展類型的命名空間搞成一致。
{
public static class MyHtmlHelper
{
public static string MyLabel(this HtmlHelper helper, string lbText)
{
return string.Format("<p>{0}</p>", lbText);
}
}
}
調用:
<%: Html.MyMvcHtmlStringLabel("sssssssskkkkkkkkkkk") %>
HTML的擴展方法:
//HtmlHelper中遇到了MvcHtmlString時候,不進行編碼化處理。
public static HtmlString MyMvcHtmlStringLabel(this HtmlHelper helper, string lbText)
{
string str = string.Format("<p>{0}</p>", lbText);
return new HtmlString(str);
}
調用:
<%: Html.MyMvcHtmlStringLabel("sssssssskkkkkkkkkkk") %>
弱類型視圖中傳遞ID的方法:
public ActionResult ShowCustomer(int id)
{
//根據id獲取 當前的Customer
Customer customer = new Customer() { Id = id, Age = 18, Email = "110@itcast.cn", SName = "yang" };
ViewData["Customer"] = customer;
return View();
}
UI接受:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<%@ Import Namespace="MvcDemo2.Models" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>ShowCustomer</title>
</head>
<body>
<div>
<% var customer = ViewData["Customer"] as Customer; %>
<table>
<tr>
<td>顧客編號:</td><td><%= customer.Id %></td>
</tr>
<tr>
<td>顧客名:</td><td><%= customer.SName %></td>
</tr>
<tr>
<td>顧客Age:</td><td><%= customer.Age %></td>
</tr>
<tr>
<td>顧客郵箱:</td><td><%= customer.Email %></td>
</tr>
</table>
</div>
</body>
</html>
強類型:
#region 強類型頁面的方式
public ActionResult Detail(int id)
{
//Customer customer = new Customer() { Id = id, Age = 18, Email = "110@itcast.cn", SName = "yang" };
//傳一個集合的方法
List<MvcDemo2.Models.Customer> list = new List<Customer>()
{
new Customer() { Id = id, Age = 18, Email = "110@itcast.cn", SName = "yang" }
};
// ViewData["sss"] = "sssssss";
// ViewData.Model = customer;
ViewData .Model= list;
return View();
}
#endregion
頁面:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcDemo2.Models.Customer>" %>
<%--<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<List<MvcDemo2.Models.Customer>>" %>--%>
<%@ Import Namespace="MvcDemo2.Models" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Detail</title>
</head>
<body>
<div>
<table>
<tr>
<td>顧客編號:</td><td><%: Model.Id %>
<%--<%: Html.TextBox("Id") %>--%>
<%-- <%: Html.TextBoxFor(c=>c.Id) %>--%>
</td>
</tr>
<tr>
<%-- <td>顧客名:</td><td><%= Model.SName %></td>--%>
<td>顧客名:</td><td><%= Model.SName %></td>
</tr>
<tr>
<%-- <td>顧客Age:</td><td><%= Model.Age %></td>--%>
<td>顧客Age:</td><td><%= Model.Age %></td>
</tr>
<tr>
<%-- <td>顧客郵箱:</td><td><%= Model.Email %></td>--%>
<td>顧客郵箱:</td><td><%= Model.Email %></td>
</tr>
</table>
</div>
</body>
</html>
MVC的增刪該查:
DataModel:通過表來的
ViewModel:跟頁面的表單和頁面展示的內容相關
public class ClassInfoController : Controller
{
//
// GET: /ClassInfo/
CodeDbEntities dbContext = new CodeDbEntities();
public ActionResult Index(int pageIndex=1,int pageSize=2)
{
//int pageSize = int.Parse(Request["pageSize"] ?? "2");
ViewData["pageIndex"] = pageIndex;
ViewData["pageSize"] = pageSize;
ViewData["total"] = dbContext.ClassInfoes.Count();
//ViewData.Model = dbContext.ClassInfoes.AsEnumerable();
ViewData.Model = dbContext.ClassInfoes
.OrderBy(u => u.Id)
.Skip(pageSize*(pageIndex - 1))
.Take(pageSize).AsEnumerable();
return View();
}
#region Details
public ActionResult Details(int id)
{
//ViewData.Model = dbContext.ClassInfoes.Where(u => u.Id == id).FirstOrDefault();
ViewData.Model = dbContext.ClassInfoes.Find(id);
return View();
}
#endregion
#region Delete
public ActionResult Delete(int id)
{
ViewData.Model = dbContext.ClassInfoes.Find(id);
return View();
}
[HttpPost]
public ActionResult Delete(int id,FormCollection collection)
{
//把數據刪除
ClassInfoes classInfoes =new ClassInfoes();
classInfoes.ClassInfoName = string.Empty;
classInfoes.Id = id;
dbContext.ClassInfoes.Attach(classInfoes);
dbContext.Entry(classInfoes).State = EntityState.Deleted;
dbContext.SaveChanges();
return RedirectToAction("Index");
}
#endregion
#region Create
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(ClassInfoes classInfoes)
{
dbContext.ClassInfoes.Add(classInfoes);
dbContext.SaveChanges();
return RedirectToAction("Index");
}
#endregion
#region Edit
public ActionResult Edit(int id)
{
ViewData.Model = dbContext.ClassInfoes.Find(id);
return View();
}
[HttpPost]
public ActionResult Edit(int id, ClassInfoes classInfoes)
{
dbContext.Entry(classInfoes).State = EntityState.Modified;
dbContext.SaveChanges();
return RedirectToAction("Index");
}
#endregion
}
添加:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcDemo2.Models.ClassInfoes>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Create</title>
</head>
<body>
<script src="<%: Url.Content("~/Scripts/jquery-1.7.1.min.js") %>"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>"></script>
<% using (Html.BeginForm()) { %>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>ClassInfoes</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.ClassInfoName) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.ClassInfoName) %>
<%: Html.ValidationMessageFor(model => model.ClassInfoName) %>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
</body>
</html>
刪除:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcDemo2.Models.ClassInfoes>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Delete</title>
</head>
<body>
<h3>Are you sure you want to delete this?</h3>
<fieldset>
<legend>ClassInfoes</legend>
<div class="display-label">
<%: Html.DisplayNameFor(model => model.ClassInfoName) %>
</div>
<div class="display-field">
<%: Html.DisplayFor(model => model.ClassInfoName) %>
</div>
</fieldset>
<% using (Html.BeginForm()) { %>
<p>
<input type="submit" value="Delete" /> |
<%: Html.ActionLink("Back to List", "Index") %>
</p>
<% } %>
</body>
</html>
詳情:
<%--<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcDemo2.Models.Customer>" %>--%>
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<List<MvcDemo2.Models.Customer>>" %>
<%@ Import Namespace="MvcDemo2.Models" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Detail</title>
</head>
<body>
<div>
<table>
<tr>
<td>顧客編號:</td><td><%: Model.Customer.ID%>
<%--<%: Html.TextBox("Id") %>--%>
<%-- <%: Html.TextBoxFor(c=>c.Id) %>--%>
</td>
</tr>
<tr>
<%-- <td>顧客名:</td><td><%= Model.SName %></td>--%>
<td>顧客名:</td><td><%= Model.Customer.Name %></td>
</tr>
<tr>
<%-- <td>顧客Age:</td><td><%= Model.Age %></td>--%>
<td>顧客Age:</td><td><%= Model.Customer.Age %></td>
</tr>
<tr>
<%-- <td>顧客郵箱:</td><td><%= Model.Email %></td>--%>
<td>顧客郵箱:</td><td><%= Model.Customer.Email %></td>
</tr>
</table>
</div>
</body>
</html>
分頁:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcDemo2.Models.ClassInfoes>>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<p>
<%: Html.ActionLink("Create New", "Create") %>
</p>
<table>
<tr>
<th>
Id
</th>
<th>
<%: Html.DisplayNameFor(model => model.ClassInfoName) %>
</th>
<th></th>
</tr>
<% foreach (var item in Model) { %>
<tr>
<td>
<%: item.Id %>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.ClassInfoName) %>
</td>
<td>
<%: Html.ActionLink("Edit", "Edit", new { id=item.Id }) %> |
<%: Html.ActionLink("Details", "Details", new { id=item.Id }) %> |
<%: Html.ActionLink("Delete", "Delete", new { id=item.Id }) %>
</td>
</tr>
<% } %>
</table>
<div id="pageNav">
<%: Html.ShowPageNavigate((int)ViewData["pageIndex"],(int)ViewData["pageSize"],(int)ViewData["total"]) %>
</div>
</body>
</html>
HTML分頁的擴展方法:
//主要就是輸出分頁的超級鏈接的標簽
//自定義分頁Helper擴展
public static HtmlString ShowPageNavigate(this HtmlHelper htmlHelper, int currentPage, int pageSize, int totalCount)
{
var redirectTo = htmlHelper.ViewContext.RequestContext.HttpContext.Request.Url.AbsolutePath;
pageSize = pageSize == 0 ? 3 : pageSize;
var totalPages = Math.Max((totalCount + pageSize - 1) / pageSize, 1); //總頁數
var output = new StringBuilder();
if (totalPages > 1)
{
//if (currentPage != 1)
{//處理首頁連接
output.AppendFormat("<a class='pageLink' href='{0}?pageIndex=1&pageSize={1}'>首頁</a> ", redirectTo, pageSize);
}
if (currentPage > 1)
{//處理上一頁的連接
output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>上一頁</a> ", redirectTo, currentPage - 1, pageSize);
}
else
{
// output.Append("<span class='pageLink'>上一頁</span>");
}
output.Append(" ");
int currint = 5;
for (int i = 0; i <= 10; i++)
{//一共最多顯示10個頁碼,前面5個,后面5個
if ((currentPage + i - currint) >= 1 && (currentPage + i - currint) <= totalPages)
{
if (currint == i)
{//當前頁處理
//output.Append(string.Format("[{0}]", currentPage));
output.AppendFormat("<a class='cpb' href='{0}?pageIndex={1}&pageSize={2}'>{3}</a> ", redirectTo, currentPage, pageSize, currentPage);
}
else
{//一般頁處理
output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>{3}</a> ", redirectTo, currentPage + i - currint, pageSize, currentPage + i - currint);
}
}
output.Append(" ");
}
if (currentPage < totalPages)
{//處理下一頁的鏈接
output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>下一頁</a> ", redirectTo, currentPage + 1, pageSize);
}
else
{
//output.Append("<span class='pageLink'>下一頁</span>");
}
output.Append(" ");
if (currentPage != totalPages)
{
output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>末頁</a> ", redirectTo, totalPages, pageSize);
}
output.Append(" ");
}
output.AppendFormat("第{0}頁 / 共{1}頁", currentPage, totalPages);//這個統計加不加都行
return new HtmlString(output.ToString());
}
MVC異步
$(function () {
$("#loadingDiv").css("display", "none");
$("#bntJQAjax").click(function () {
$.ajax({
url: "/Ajax/Date", type: "Post",
data: {},
success: function (data) {
alert(data);
}
});
});
});
<input type="submit" value="獲取日期" />
public ActionResult Date()
{
return Content(DateTime.Now.ToString());
}
MVC自帶的異步:
需要引入的js
<script src="../../Scripts/jquery-1.7.1.js"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript">
$(function () {
$("#loadingDiv").css("display", "none");
$("#bntJQAjax").click(function () {
$.ajax({
url: "/Ajax/Date", type: "Post",
data: {},
success: function (data) {
alert(data);
}
});
});
});
$(function () {
$("#loadingDiv").css
})
function afterSuccess(data) {
//alert(data);
}
</script>
<form action="/Ajax/Date" data-ajax="true" data-ajax-confirm="您確認提交嗎》?" data-ajax-loading="#loadingDiv" data-ajax-method="Post" data-ajax-mode="replace" data-ajax-success="afterSuccess" data-ajax-update="#resultDiv" id="form0" method="post" enctype="multipart/form-data">
<input type="text" name="txtName" />
<br />
<input type="submit" value="獲取日期" />
<input type="file" name="ss" />
</form>
隱式的按鈕點擊庫:
$(function () {
$("btn").click(function () {
});
// 隱式的按鈕點擊庫
$("input[btn-click]").click(function () {
var strFunc = $(this).attr("btn-click");
eval(strFunc + "()");
});
});
異步和同步上傳圖片:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>ImageUpload</title>
<script src="../../Scripts/jquery-1.7.1.js"></script>
<%--<script src="../../Scripts/jquery.unobtrusive-ajax.js"></script>--%>
<%--<script src="../../Scripts/MicrosoftAjax.js"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js"></script>--%>
<script src="../../Scripts/MyAjaxForm.js"></script>
<script type="text/javascript">
function afterUpload(data) {
$("#result").html("<img src='"+data+"' />");
}
$(function () {
$("#btnSub").click(function() {
$("#frm").ajaxSubmit({
url: "/Ajax/ProcessImgUpload",
type: "Post",
success: afterUpload
});
return false;
});
});
</script>
</head>
<body>
<div>
<%-- <% using (Ajax.BeginForm("ProcessImgUpload","Ajax",new AjaxOptions()
{
HttpMethod = "Post",
OnSuccess = "afterUpload"
}, new { enctype = "multipart/form-data" }))
{ %>
--%>
<form action="/Ajax/ProcessImgUpload" method="POST" enctype="multipart/form-data" id="frm">
<input type="file" id="img" name="imgFile" />
<input type="submit" id="btnSub" value="異步上傳圖片"/>
</form>
<%-- <% } %>--%>
<div id="result">
</div>
</div>
</body>
</html>
后台:
public ActionResult ImageUpload()
{
return View();
}
public ActionResult ProcessImgUpload()
{
var file= Request.Files["imgFile"];
string path = "/Upload/"+Guid.NewGuid().ToString()+ file.FileName;
file.SaveAs(Request.MapPath(path));
return Content(path);
}
