至於沒用過的可試試,只要在專案上按下右鍵如下圖及可搜尋及安裝

但像jQuery有很多版本確不想要安裝到最新的版本那怎麼辦?
到jquery點選下面的版本
會有一行 PM > Install-Package jQuery -Version 1.10.2


$(function () { $("#<%= Master.ClientID%>").change(function () { var q = $("#<%= Master.ClientID%>").val(); $.ajax({ url: '/get.ashx', type: 'post', async: true, data: { q: q }, success: function (data) { $('#<%= Detail.ClientID%>').empty(); var myarray = $.parseJSON(data); $.each(myarray, function (i, item) { var option = "<option value='" + myarray[i].value + "'>" + myarray[i].txt + "</option>"; $('#<%= Detail.ClientID%>').append(option); }); } }); }); });上面程式碼看似無誤,但在PostBack後就會出現System.Web.HttpUnhandledException
$(function () { }); $("#<%= Master.ClientID%>").change(function () { var q = $("#<%= Master.ClientID%>").val(); $.ajax({ url: '/get.ashx', type: 'post', async: true, data: { q: q }, success: function (data) { $('#<%= Detail.ClientID%>').empty(); var myarray = $.parseJSON(data); $.each(myarray, function (i, item) { var option = "<option value='" + myarray[i].value + "'>" + myarray[i].txt + "</option>"; $('#<%= Detail.ClientID%>').append(option); }); } }); });
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", mFileName));
Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", mFileName));多加了分雙引號這樣輸出的標頭才會指定檔名是什麼減少攻擊
function formatSecond(secs) { var hr = Math.floor(secs / 3600); var min = Math.floor((secs - (hr * 3600)) / 60); var sec = parseInt( secs - (hr * 3600) - (min * 60)); while (min.length < 2) { min = '0' + min; } while (sec.length < 2) { sec = '0' + sec; } if (hr) hr += ':'; return hr + min + ':' + sec; }參考網址 點我
<elmah> <security allowRemoteAccess="1" /> </elmah>3.以下是幾個設定在相關教學裡有保哥說的很詳細
<appSettings> <add key="elmah.mvc.disableHandler" value="false" /> <add key="elmah.mvc.disableHandleErrorFilter" value="false" /> <add key="elmah.mvc.requiresAuthentication" value="true" /> <add key="elmah.mvc.allowedRoles" value="*" /> <add key="elmah.mvc.route" value="errorelmah" /> </appSettings>參考網址
//抓最大值 int Sort = (from u in db.TabContent where u.TabID==tabid select u.Sort).DefaultIfEmpty().Max(x => x == null ? 0 : x); ViewBag.Sort = Sort + 1;以上這部份很簡單沒問題吧
<div class="form-group"> @Html.LabelFor(model => model.Sort, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextBoxFor(model => model.Sort) @Html.ValidationMessageFor(model => model.Sort) </div> </div>程式碼自動產生會這樣
<div class="form-group"> @Html.LabelFor(model => model.Sort, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextBox("Sort",null, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Sort) </div> </div>改成用弱型別是一個方法記得"Sort"這樣就能抓到ViewBag了
public ActionResult Index( ) { ViewBag.TabData = new SelectList(db.Tab, "TabID", "TabName"); //產生下拉選單 return View(); }View的部份也放一個@Html.DropDownList接收下拉選單
@Html.DropDownList("TabData", null, null, new { id = "ddTabData" })然後產原本產生的Index裡的Table另外開一個_List.schtml裡
$(function () { $("#ddTabData").change(function () { var selectedItem = $("#ddTabData").val(); $.ajax({ cache: false, type: "GET", url: "@(Url.Action("GetList", "TabContent", null))", data: { "tid": selectedItem }, success: function (data) { $("#Content").html(data); }, error: function (xhr, ajaxOptions, thrownError) { alert('讀取資料失敗.'); } }); }); });去呼叫@(Url.Action("GetList", "TabContent", null))
public ActionResult GetList(int tid = 1) { var tabcontent = db.TabContent.Where(u => u.TabID == tid).Include(t => t.Account).Include(t => t.Account1).Include(t => t.Tab); return View("_List",tabcontent.ToList() ); }這樣就會回傳一整個Table回來
@{ if (IsAjax) { Layout = null; } }上面這句也要加,不加差在那邊各位可以自己測試!!
public ActionResult Index() { Mapper.CreateMap<Account, AccountMV>(); var OrderList = db.Account.OrderBy(o => o.AccountID);//設定OrderBy List var PagedList = OrderList.ToPagedList(p, 2);//分頁的 List var viewmodel = Mapper.Map<IEnumerable<Account>, IEnumerable<AccountMV>>(PagedList.ToArray()); // 分頁列表轉換成ViewModel var query = new StaticPagedList<AccountMV>(viewmodel, PagedList.GetMetaData()); // reconsitute a new IPagedList containing the viewmodels return View(query); }說真的我還真看不太懂最後一行那句
public ActionResult Index() { var query = from u in db.Account select new AccountVM { AccountID = u.AccountID, AccountName = u.AccountName, IsUsed = u.IsUsed, LoginIP = u.LoginIP, LoginDate = u.LoginDate, Name = u.Name, Email = u.Email }; return View(query); }看以上程式碼只要加一個欄位每次都要跑來修改
public ActionResult Index() { Mapper.CreateMap<Account, AccountVM>(); List<Account> account = db.Account.ToList(); List< AccountVM> query = Mapper.Map< List< Account>,List< AccountVM>>(account); return View(query); }這樣不管怎麼增加欄位都不需要在Controller修改了
@{ List<SelectListItem> list = (List<SelectListItem>)ViewBag.TabColumnName; foreach (var s in list ) { if (item.TabColumnName.Equals(s.Value)) { s.Selected = true; } else { s.Selected = false; } } } @Html.DropDownListFor(modelItem => item.TabColumnName, list)Controller如下
ViewBag.TabColumnName =TabColumnVM.getTabColumnName();
public ActionResult Delete(short? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } //重點在這裡接收後顯示錯誤 if (TempData["CustomError"] != null) { ModelState.AddModelError(string.Empty, TempData["CustomError"].ToString()); } //Account account = db.Account.Find(id); var query = from u in db.Tab where u.TabID == id; if (query == null) { return HttpNotFound(); } return View(query); } [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(short? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } string Sql = " TabID == @0"; var query1 = (from u in db.TabColumn.Where(Sql, id) select u).ToList(); if (query1.Count() > 0) { //有錯時丟給Get顯示 TempData["CustomError"] = "頁籤內有欄位所以不可刪除"; return RedirectToAction("Delete",null, id); } Tab query = db.Tab.Find(id); db.Tab.Remove(query); db.SaveChanges(); return RedirectToAction("Index"); }在View裡記得加以下才會顯喔
@Html.ValidationSummary(true)參考網址
[DisplayName("時間")] [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm:ss}", ApplyFormatInEditMode = false)] public Nullable以上在list用DisplayFor都沒什麼問題pDate { get; set; }
@Html.TextBoxFor(model => model.LoginDate, "{0:yyyy-MM-dd HH:mm:ss}", new { @class = "form-control", @readonly = "readonly" })參考網址
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(int Id, AccountEdit Form) { if (ModelState.IsValid) { Account query = db.Account.Find(Id); List<string> list = new List<string>(); // 沒打 是空時 時不更新 if (Form.Password == null || Form.Password.ToString().Equals("")) { list.Add("Password"); } if (TryUpdateModel(query,"",null,list.ToArray())) { try { // 有打時 不是空 這段必需要寫在TryUpdateModel if (Form.Password != null && !Form.Password.ToString().Equals("")) { query.Password = PublicFunction.EncodeStringMD5(Form.Password); } db.SaveChanges(); } catch (Exception ex) { string e = ex.Message.ToString(); throw; } return RedirectToAction("Index"); } return View(query); } return View(Form); }有個特別的地方就是要輸入時才更新密碼部份
public class TabContainerVM public class TabContainerVM { public IEnumerable在Controller裡把資料自行加入到model裡後回傳tab { get; set; } public IEnumerable tabcolumn { get; set; } public IEnumerable tabrow { get; set; } }
> public ActionResult TabContainer() { var tab = from u in db.Tab select u; var tabcolumn = from u in db.TabColumn select u; var tabrow = from u in db.TabRow select u; var model = new TabContainerVM { tab = tab, tabcolumn = tabcolumn, tabrow = tabrow }; return PartialView("_TabContainer",model); }view的話就能使用
@model ViewModels.TabContainerVM <div> @foreach (var tab in Model.tab) { <ul> @foreach (var tab in Model.tabcolumn ) { //do something <li></li> } </ul> } </div>參考網址 點我
@RenderBody()RenderSection在_Layout裡可以有許多的RenderSection
@RenderSection("head",required: false)一般頁面
@section head{ //你的程式碼 }
@section head{ }在執行後Partial裡的程式碼完全不會顯示
if ( User.Identity.IsAuthenticated) { //這邊是有驗證過已登入 }如果是一整個Controller都需要驗證可加[Authorize]在Class上
[Authorize] public class HomeController : Controller { [AllowAnonymous] public ActionResult Index() { ViewBag.Title = PublicFunction.WebSiteName; return View(); } public ActionResult Create() { return View(); } }以下是登出的完整程式碼
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Logout() { FormsAuthentication.SignOut(); Session.Abandon(); // clear authentication cookie HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, ""); cookie1.Expires = DateTime.Now.AddYears(-1); Response.Cookies.Add(cookie1); // clear session cookie (not necessary for your current problem but i would recommend you do it anyway) HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", ""); cookie2.Expires = DateTime.Now.AddYears(-1); Response.Cookies.Add(cookie2); //FormsAuthentication.RedirectToLoginPage(); return RedirectToAction("Index", "Home", null); }參考網站
bundles.Add(new ScriptBundle("~/bundles/fancybox").Include("~/Scripts/fancybox/jquery.fancybox.js")); bundles.Add(new StyleBundle("~/Content/fancybox").Include("~/Content/fancybox/jquery.fancybox.css"));View的部份新增兩個一個為主頁面(Index)一個為被呼叫頁面(FancyBox)
<script src="~/Scripts/jquery-1.10.2.min.js"></script> @Scripts.Render("~/bundles/fancybox") @Styles.Render("~/Content/fancybox") @Html.ActionLink("[新增]", "FancyBox", "Home", null, new { @class = "fancybox fancybox.iframe" }) <script> $(function () { $('.fancybox').fancybox(); }); </script>
@using (Html.BeginForm("Index", "Home", FormMethod.Post)) { @Html.TextArea("abc") <input type="submit" value="送出" /> }再加入參考js及寫script
<!--http://www.tinymce.com/i18n/--> <!--http://www.tinymce.com/tryit/classic.php--> <script src="~/Scripts/tinymce/tinymce.min.js"></script> <script> tinymce.init({ selector: 'textarea', //設定那一個標籤會用 language: "zh_tw", //語言 plugins: [ "advlist autolink autosave link image lists charmap print preview hr anchor pagebreak spellchecker", "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking", "table contextmenu directionality emoticons template textcolor paste fullpage textcolor" ],//設定須要那些外掛 toolbar1: "newdocument fullpage | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | styleselect formatselect fontselect fontsizeselect", toolbar2: "cut copy paste | searchreplace | bullist numlist | outdent indent blockquote | undo redo | link unlink anchor image media code | inserttime preview | forecolor backcolor", toolbar3: "table | hr removeformat | subscript superscript | charmap emoticons | print fullscreen | ltr rtl | spellchecker | visualchars visualblocks nonbreaking template pagebreak restoredraft", toolbar_items_size: 'small'//小圖的ToolBar }); </script>在action裡接收程式碼如下
[HttpPost] [ValidateInput(false)] public ActionResult Index(FormCollection form) { if(ModelState.IsValid) { string test = form["abc"]; } return View(); }
<p></p>而在MVC中如果是以欄位
@item.content來輸出裡面有
則會備程式編成html 所以需搭配
@Html.Raw(@item.content)
//先using以下兩個命名空間 using System.ComponentModel.DataAnnotations; using System.ComponentModel;以下幾個例子大概都包含了常用的
public class AccountInfo { [Key] public int AccountID { get; set; } [DisplayName("登入帳號")] [Required(ErrorMessage = "請輸入登入帳號")] [StringLength(40, ErrorMessage = "登入帳號最多20個字")] public string AccountName { get; set; } [DisplayName("密碼")] [Required(ErrorMessage = "請輸入密碼")] [MaxLength(20, ErrorMessage = "密碼最多20個字")] [MinLength(8, ErrorMessage = "密碼最少8個字")] [DataType(DataType.Password)] public string Password { get; set; } [DisplayName("確認密碼")] [DataType(DataType.Password)] [Compare("Password", ErrorMessage = "密碼與確認密碼不符")] public int ConfirePassword { get; set; } [DisplayName("姓名")] [StringLength(10, ErrorMessage = "姓名最多10個字")] public string Name { get; set; } [DisplayName("生日")] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")] public DateTime BirthDay { get; set; } [DisplayName("年齡")] [Range(1,100,ErrorMessage="年齡請輸入1~100歲")] public int Age { get; set; } [DisplayName("電子郵件")] [EmailAddress(ErrorMessage="信箱格式錯誤")] public string Email { get; set; } [DisplayName("個人部落格")] [Url (ErrorMessage="連結格式錯誤")] public string BolgUrl { get; set; } [DisplayName("薪資")] [RegularExpression(@"^d+$", ErrorMessage = "請輸入數字.")] public int Salary { get; set; } }
app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login") });5.新增一個ViewModels資料夾來存放自己定義的model 加入
using System.ComponentModel.DataAnnotations; using System.ComponentModel;定義Model
public class Login { [DisplayName("登入帳號")] [Required(ErrorMessage = "請輸入登入帳號")] [StringLength(40, ErrorMessage = "登入帳號最多20個字")] public string AccountName { get; set; } [DisplayName("登入密碼")] [Required(ErrorMessage = "請輸入登入密碼")] [StringLength(40, ErrorMessage = "密碼最多20個字")] [DataType(DataType.Password)] public string Password { get; set; } }Login的畫面
@using (Html.BeginForm("Login", "Login", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post)) { @Html.AntiForgeryToken() @*@Html.ValidationSummary()*@ <h3>後台登入</h3> <div class="logintype"> @Html.LabelFor(model => model.AccountName, new { @class = "control-label" }) <div class="controls"> @Html.TextBoxFor(model => model.AccountName, new { @class = "form-control", placeholder = "請輸入登入帳號" }) @Html.ValidationMessageFor(model => model.AccountName, null, new { @class = "help-inline" }) </div> </div> <div class="logintype"> @Html.LabelFor(model => model.Password, new { @class = "control-label" }) <div class="controls"> @Html.PasswordFor(model => model.Password, new { @class = "form-control", placeholder = "請輸入登入密碼" }) @Html.ValidationMessageFor(model => model.Password, null, new { @class = "help-inline" }) </div> </div> <div class="logintype"> @TempData["Error"] </div> <input type="submit" name="button" value="登入"> }登入的Action
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Login(Login form) { if (ModelState.IsValid) { //驗證資料庫登入 //這邊請使用自行驗證摟 string Sql = " AccountName == @0 and Password == @1 and IsUsed == @2"; var query = (from u in db.Account.Where(Sql, form.AccountName, form.Password, "true") select u).ToList(); if (query.Count() != 1) { ModelState.AddModelError(string.Empty, "帳號或密碼錯誤登入失敗"); return View("Index",form); } try { query[0].LoginIP =PublicFunction.GetIpAddress(); query[0].LoginDate = DateTime.Now; db.SaveChanges(); } catch (Exception ex) { ModelState.AddModelError(string.Empty, ex.Message.ToString()); return View("Index", form); } bool isPersistent = false;//如果票證將存放於持續性 Cookie 中 (跨瀏覽器工作階段儲存),則為 true,否則為 false。 如果票證是存放於 URL 中,則忽略這個值。 string userData = "";//可放使用者自訂的內容 string mAccountID = query[0].AccountID.ToString(); //寫cookie //使用 Cookie 名稱、版本、到期日、核發日期、永續性和使用者特定的資料,初始化 FormsAuthenticationTicket 類別的新執行個體。 此 Cookie 路徑設定為在應用程式的組態檔中建立的預設值。 //使用 Cookie 名稱、版本、目錄路徑、核發日期、到期日期、永續性和使用者定義的資料,初始化 FormsAuthenticationTicket 類別的新執行個體。 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, mAccountID,//使用者ID DateTime.Now,//核發日期 DateTime.Now.AddMinutes(1800),//到期日期 30分鐘 isPersistent,//永續性 userData,//使用者定義的資料 FormsAuthentication.FormsCookiePath); string encTicket = FormsAuthentication.Encrypt(ticket); Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); //HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); //cookie.Expires = ticket.Expiration; //Response.Cookies.Add(cookie); //FormsAuthentication.RedirectFromLoginPage(strUsername, isPersistent); if (form.ReturnUrl != null) { return Redirect(form.ReturnUrl.ToString()); } else { return RedirectToAction("Index", "Admin"); } } //return RedirectToAction("Index", "Login", null); return View("Index", form); }最後再需要驗證的Class上加[Authorize] 雖然大部份程式碼都是copy來的
<authentication mode="None" />修改成
<authentication mode="Forms"> <forms loginUrl="/Login" path="/"></forms> </authentication>
public ActionResult Index(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(); }
public override void ExecuteResult(ControllerContext context) { var properties = new AuthenticationProperties() { RedirectUri = RedirectUri }; if (UserId != null) { properties.Dictionary[XsrfKey] = UserId; } context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider); }改為
public override void ExecuteResult(ControllerContext context) { //多下列這行 context.RequestContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true; var properties = new AuthenticationProperties() { RedirectUri = RedirectUri }; if (UserId != null) { properties.Dictionary[XsrfKey] = UserId; } context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider); }參考網址
Button1.OnClientClick = "return confirm('您確定要刪除嗎??\\n\\r刪除後將無法復原!!');";
重點再於一個\\n\\r在程式中為什麼要\\呢如果在網頁內就直接寫\n\r即可
var d = new Date(); var month = d.getMonth() + 1; var day = d.getDate(); var hour = d.getHours(); var minutes = d.getMinutes(); var seconds = d.getSeconds(); var NowDate = d.getFullYear() + '-' + toTen(month) + '-' + toTen(day); var Now = d.getFullYear() + '-' + toTen(month) + '-' + toTen(day) + ' ' + toTen(hour) + ":" + toTen(minutes)+":" +toTen(seconds); alert(NowDate); alert(Now); function toTen(s) { return s < 10 ? '0' + s : s; }
<input type="text" name="text" placeholder="請輸入" id="text" x-webkit-speech x-webkit-grammar="bUIltin:search" />
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="" Inherits="" MaintainScrollPositionOnPostback="true" %>加上MaintainScrollPositionOnPostback="true"
var modified = false; $(function () { $("input,select,textarea").change(function () { modified = true; }); $("input:submit").click(function () { modified = false; }); }); window.onbeforeunload = function confirmExit() { if (modified) return '有尚未儲存的資料,確定要離開嗎?'; }
資料來源
using System.Web.SessionState; public class checkCookie : IHttpHandler , IRequiresSessionState這樣就能使用session啦