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

但像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 = ""; $('#<%= 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 = ""; $('#<%= 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; }參考網址 點我
//抓最大值 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;以上這部份很簡單沒問題吧
程式碼自動產生會這樣@Html.LabelFor(model => model.Sort, new { @class = "control-label col-md-2" })@Html.TextBoxFor(model => model.Sort) @Html.ValidationMessageFor(model => model.Sort)
改成用弱型別是一個方法記得"Sort"這樣就能抓到ViewBag了@Html.LabelFor(model => model.Sort, new { @class = "control-label col-md-2" })@Html.TextBox("Sort",null, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Sort)
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裡
去呼叫@(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說真的我還真看不太懂最後一行那句(); var OrderList = db.Account.OrderBy(o => o.AccountID);//設定OrderBy List var PagedList = OrderList.ToPagedList(p, 2);//分頁的 List var viewmodel = Mapper.Map , IEnumerable >(PagedList.ToArray()); // 分頁列表轉換成ViewModel var query = new StaticPagedList (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這樣不管怎麼增加欄位都不需要在Controller修改了(); List account = db.Account.ToList(); List< AccountVM> query = Mapper.Map< List< Account>,List< AccountVM>>(account); return View(query); }
@{ ListController如下list = (List )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)
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有個特別的地方就是要輸入時才更新密碼部份list = new List (); // 沒打 是空時 時不更新 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參考網址 點我@foreach (var tab in Model.tab) {@foreach (var tab in Model.tabcolumn ) { //do something }
}
@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)
@Scripts.Render("~/bundles/fancybox") @Styles.Render("~/Content/fancybox") @Html.ActionLink("[新增]", "FancyBox", "Home", null, new { @class = "fancybox fancybox.iframe" })
@using (Html.BeginForm("Index", "Home", FormMethod.Post)) { @Html.TextArea("abc") }再加入參考js及寫script
在action裡接收程式碼如下
[HttpPost] [ValidateInput(false)] public ActionResult Index(FormCollection form) { if(ModelState.IsValid) { string test = form["abc"]; } return View(); }
而在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()*@登入的Action後台登入
@Html.LabelFor(model => model.AccountName, new { @class = "control-label" })@Html.TextBoxFor(model => model.AccountName, new { @class = "form-control", placeholder = "請輸入登入帳號" }) @Html.ValidationMessageFor(model => model.AccountName, null, new { @class = "help-inline" })@Html.LabelFor(model => model.Password, new { @class = "control-label" })@Html.PasswordFor(model => model.Password, new { @class = "form-control", placeholder = "請輸入登入密碼" }) @Html.ValidationMessageFor(model => model.Password, null, new { @class = "help-inline" })@TempData["Error"]}
[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來的
修改成
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
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"
using System.Web.SessionState;
public class checkCookie : IHttpHandler ,IRequiresSessionState
這樣就能使用session啦