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

但像jQuery有很多版本確不想要安裝到最新的版本那怎麼辦?
到jquery點選下面的版本
會有一行 PM > Install-Package jQuery -Version 1.10.2
到VS > 工具 > 程式庫套件管理員 >套件管理主控台 > 點一下就會出現主控台視窗 將剛的那一樣貼上執行即可

$(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 pDate { get; set; }
以上在list用DisplayFor都沒什麼問題
@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 tab { get; set; }
public IEnumerable tabcolumn { get; set; }
public IEnumerable tabrow { get; set; }
}
在Controller裡把資料自行加入到model裡後回傳
>
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>