ASP.NET MVC,參照:『維基百科~ASP.NET_MVC』
技術文件
應用
資料分頁
WYSIWYG HTML Editors
FAQ
ASP.NET WebForm 與 ASP.NET MVC 共存
- 先開1個ASP.NET MVC4應用程式專案, 再從專案裡加入Web
- 在Web裡,建立 App_Code 資料夾,把App_Start、Controllers、Filters、Models 等資料夾都搬進去
- 使用NuGet把Web加入MVC4應用程式所引用的套件(已安裝套件→全部→管理)
- 改寫 Global.asax 成單一檔案
<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// 應用程式啟動時執行的程式碼
//TODO:
System.Data.Entity.Database.SetInitializer<MvcApp1.Models.UsersContext>(null);
//TODO: 預設
AreaRegistration.RegisterAllAreas();
MvcApp1.WebApiConfig.Register(System.Web.Http.GlobalConfiguration.Configuration);
MvcApp1.FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
MvcApp1.RouteConfig.RegisterRoutes(RouteTable.Routes);
MvcApp1.BundleConfig.RegisterBundles(BundleTable.Bundles);
MvcApp1.AuthConfig.RegisterAuth();
Application.Lock();
//線上人數
Application["CountOfOnline"] = 0;
Application.UnLock();
}
void Application_End(object sender, EventArgs e)
{
// 應用程式關閉時執行的程式碼
}
void Application_Error(object sender, EventArgs e)
{
// 發生未處理錯誤時執行的程式碼
}
void Session_Start(object sender, EventArgs e)
{
// 啟動新工作階段時執行的程式碼
Application.Lock();
int CountOfOnline = int.Parse(Application["CountOfOnline"].ToString());
CountOfOnline++;
Application["CountOfOnline"] = CountOfOnline;
Application.UnLock();
}
void Session_End(object sender, EventArgs e)
{
// 工作階段結束時執行的程式碼。
// 注意: 只有在 Web.config 檔將 sessionstate 模式設定為 InProc 時,
// 才會引發 Session_End 事件。如果將工作階段模式設定為 StateServer
// 或 SQLServer,就不會引發這個事件。
Application.Lock();
int CountOfOnline = int.Parse(Application["CountOfOnline"].ToString());
CountOfOnline--;
Application["CountOfOnline"] = CountOfOnline;
Application.UnLock();
}
</script>
- 其它,改寫 \App_Code\App_Start\RouteConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcApp1
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
//TODO: ASP.NET WebForm 相關
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.IgnoreRoute("{resource}.ashx/{*pathInfo}");
routes.IgnoreRoute("{resource}.ascx/{*pathInfo}");
//TODO: 預設
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
ASP.NET MVC4 登入驗證相關
- 關掉預設的登入驗證處理
- 在Web.config裡的<appSettings>區塊中加上
<add key="enableSimpleMembership" value="false"/>
<add key="autoFormsAuthentication" value="false"/>
- 使用Facebook或Twitter帳號登入
從ASP.NET WebFrom轉移到MVC
Model 相關
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
資料類型相關
SQL資料類型
|
Model欄位定義範例(C#)
|
Model欄位定義範例(VB.NET)
|
bit
|
[DisplayName("欄位名稱")]
[Column(TypeName = "bit")]
public bool FieldName { get; set; }
|
<DisplayName("欄位名稱")> _
<Column(TypeName = "bit")> _
Public Property FieldName() As Boolean
|
date
|
[DisplayName("欄位名稱")]
[DataType(DataType.DateTime)]
[Column(TypeName = "Date")]
[DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)]
public DateTime FieldName { get; set; }
|
<DisplayName("欄位名稱")> _
<DataType(DataType.DateTime)]> _
<Column(TypeName = "Date")> _
<DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)> _
Public Property FieldName() As DatrTime
|
money
|
[DisplayName("欄位名稱")]
[DataType(DataType.Currency)]
[Column(TypeName = "Money")]
public Decimal FieldName { get; set; }
|
<DisplayName("欄位名稱")> _
<DataType(DataType.Currency)> _
<Column(TypeName = "Money")> _
Public Property FieldName() As Decimal
|
nvarchar(max)
|
[DisplayName("欄位名稱")]
[StringLength(4000)]
public string FieldName { get; set; }
|
<DisplayName("欄位名稱")> _
<StringLength(4000)> _
Public Property FieldName() As String
|
驗證相關
其他Model宣告相關
[Column("欄位名稱")]
或
[Column("欄位名稱", TypeName = "資料類型")]
View 相關
View 如何收到 Controller 傳過來的內容?
種類 |
生命周期 |
隔離性 |
儲存於 |
跨伺服器 |
序列化
|
自訂 Model |
自訂 |
有 |
Server |
透過資料庫 |
可
|
ViewBag |
短(只存在於1個Action裡) |
有 |
Server |
無 |
|
ViewData |
短(只存在於1個Action裡) |
有 |
Server |
無 |
|
TimeData |
短 |
有 |
Server |
有(透過Session) |
視Session的設定而定
|
Session |
長(可自訂TimeOut時間) |
有 |
Server |
有 |
視Session的設定而定
|
Cookie |
自訂 |
有 |
Client |
有(同一個Domain裡的網站都可存取) |
不需要
|
Application |
長(直到網站重新啟動) |
無(所有的使用者共用) |
Server |
有 |
不需要
|
在View裡常用的控制項
在View裡自定helper函數
@{
Page.Title = "新頁面";
@helper FunBtn(string strText, string strUrl)
{
<input type='button' class='ImgBtn6' value='@strText' onclick='@MvcHtmlString.Create(string.Format("window.location.href = \"{0}\"", strUrl))' />
}
}
在View裡使用表單新增確認
Index.vbhtml
@Code
PageData("Title") = "xxx記錄"
Layout = "~/Views/Shared/_Layout.vbhtml"
End Code
@section head
@Scripts.Render("~/bundles/jquery.validate")
<script type="text/javascript">
var IsSubmit = false;
$(function () {
$("form").makeValidationInline();
});
$('#form1').submit(function () {
if (IsSubmit) {
return true;
} else {
showConfirmDlg();
return false;
}
});
function showConfirmDlg() {
$("#confirm").show('show').dialog({
modal: true,
dialogClass: "no-close",
buttons: [
{
text: "確認新增",
click: function () {
$(this).dialog("close");
IsSubmit = true;
$('#form1').trigger('submit');
}
},
{
text: "取消",
click: function () {
$(this).dialog("close");
IsSubmit = false;
}
}
]
});
}
</script>
End Section
<form id="form1" method="post">
//....表單欄位
MvcHtmlString.Create("<input type='button' id='ButAdd' name='ButAdd' value='新增確認' style='width:152px;' onclick='showConfirmDlg();' />")
<div id="confirm" title="xxx記錄" style="display:none">
是否確認新增?
</div>
</form>
Controller 相關
避免因為Controller未實作Action而出現HTTP 404錯誤
Controller 如何從 View 收到表單內容?
- 使用 FormCollection 當傳入參數
- 使用自訂 Model 當傳入參數
ActionResult 可回傳的種類
- View()
- PartialView()
- EmptyResult()
- Content()
- File()
- JavaScript()
- Json()
- Redirect()
- RedirectToAction()、RedirectToActionPermanent()、RedirectToRoute()、RedirectToRoutePermanent()
- HttpStatusCodeResult()、HttpNotFound()、HttpUnauthorizedResult()
- 注意:
- 因為RedirectToAction()無法傳遞 ViewBag 所以要改用 TempData 傳遞
使用Filter達到限定本機或限定IP存取
在ASP.NET MVC5 瀏覽器會一直跳 arterySignalR 相關錯誤
編譯網站時出現 警告 BC40056
- 以 VB.NET 寫 ASP.NET MVC 網站,編譯時出現 警告 BC40056
- 警告 BC40056: Imports 'WebApp1' 中指定的命名空間或類型不包含任何 Public 成員,或是找不到該命名空間或類型。請確定命名空間或類型已定義,而且其中包含至少一個 Public 成員。請確定匯入的項目名稱沒有使用任何別名。
- 在網站加入一個新的類別,將其加入Namespace WebApp1
安全性相關
使用Visual Studio發佈(Publish)一個ASP.NET MVC專案,缺少*.Interop.dll
相關