1、datagrid中JS函數傳值問題:
columns:
{
field: 'TypeName', title: '分類名稱', width: 120, sortable: true,
formatter: function (value, row, index) {
var contentDetails = "<a href='' style='text-decoration: none;' onclick='showDetailsDialog(" + row.ID + ");return false'>" + value + "</a>";
return contentDetails;
}
},
注意,以上點擊事件的傳值( row.ID或者value)一般都是一個int類型,如果是所傳的值是字符串,則需要注意加轉移字符符號。例如傳值為分類名稱則應該如下代碼:
{
field: 'TypeName', title: '分類名稱', width: 120, sortable: true,
formatter: function (value, row, index) {
var contentDetails = "<a href='' style='text-decoration: none;' onclick='showDetailsDialog(\"" + value + "\");return false'>" + value + "</a>";
return contentDetails;
}
},
2、MVC @Html.DropDownList顯示默認值問題
視圖頁面代碼:
@Html.DropDownList("ClassPre", (SelectList)ViewBag.JY_Atype_ClassPre, "==請選擇上一級分類==", new { @style = "width: 60%; height: 32px" })或
@Html.DropDownList("ClassPre", (SelectList)ViewBag.JY_Atype_ClassPre, new { @style = "width: 60%; height: 32px" })
樣式也可以去掉
Controller里面的代碼:
ViewBag.JY_Atype_ClassPre = new SelectList(newList, "ID", "TypeName", model.ClassPre);
注意:控件的name和viewbag(或viewdata)不能重名。例如以上情況時:不要用ViewBag.ClassPre或ViewBag.TypeName或ViewBag.ID這樣的名稱,盡量避免這樣的重名。
3、采用一個遞歸算法格式化展示多級分類名稱
效果如下圖:
List<JY_Atype> lst = bll.selectAll();
List<JY_Atype> newList = new List<JY_Atype>();
bll.GetMyList(lst, ref newList, 0, 1); //遞歸格式化分類
ViewBag.JY_Atype_ClassPre = new SelectList(newList, "ID", "TypeName", model.ClassPre);
/// <summary>
/// 遞歸方法格式化分類
/// </summary>
/// <param name="list">需要格式化的List類型的數據</param>
/// <param name="newList">格式化后返回的List類型的數據</param>
/// <param name="step">步驟,第一次執行時為0</param>
/// <param name="PerID">這個是上一級分類的分類ID(即當前分類的的父級ID)</param>
public void GetMyList(List<JY_Atype> list, ref List<JY_Atype> newList, int step, int PerID)
{
if (list.Count == 0)
{
return;
}
string _Step = "";
for (int i = 0; i < step; i++)
{
_Step += " ";
}
_Step += "├";
foreach (JY_Atype atype in list)
{
if (atype.ClassPre == PerID)
{
int n = newList.Count;
newList.Add(atype);
newList[n].TypeName = _Step + atype.TypeName;
newList[n].ID = atype.ID;
newList[n].ClassOrder = atype.ClassOrder;
newList[n].ClassPre = atype.ClassPre;
newList[n].IsSystem = atype.IsSystem;
newList[n].Img = atype.Img;
int newstep = step + 1;
GetMyList(list, ref newList, newstep, Convert.ToInt32(atype.ID));
}
}
}
4、MVC中采用百度富文本編輯器在編輯視圖頁面新聞內容初始化為空問題:
<span style="display: none;">
<input type="hidden" id="Content" class="easyui-textbox" style="width: 100%; height: 32px; display: none;" value="@Model.content">
</span>
<script type="text/javascript">
var URL = "/ueditor/"; //這里你可以配置成ueditor目錄在您網站的相對路徑或者絕對路徑
var editor = new baidu.editor.ui.Editor({ initialFrameHeight: 280, initialFrameWidth: 750 });
editor.render("editor");
editor.ready(function() {
editor.setContent($('#Content').val());
});
</script>
5、MVC數據注釋及驗證引用
using System.ComponentModel.DataAnnotations;
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.ComponentModel.DataAnnotations.dll
6、項目中添加了MVC引用,但是一直編譯不成功,總是提示System.Web中不包含Mvc的命名:FlagType.SelectListItems
最后解決:項目.Net FrameWork版本統一。
7、對於ASP.NET設置頁面緩存:
如果頁面加了:<%@ OutputCache Duration="60" VaryByParam="none" %>,可能造成頁面分頁不正常,盡量不要采用頁面緩存。
8、JQuery EasyUI頁面輸入框事件JS:
<div class="editor-field">
<input required="true" id="PageCode" name="PageCode" value="@Model.PageCode" class="easyui-textbox" style="width: 60%; height: 32px" />
@Html.ValidationMessageFor(model => model.PageCode)
</div>
JS:
<script type="text/javascript">
$(function () {
$("input", $("#PageCode").next("span")).blur(function() {
//alert($(this).val());
var code = $(this).val();
$.post("@Url.Action("IsHavePageCode", "Sys_RolePermission")", { pagecode: code }, function (data) {
if (data.toString() == "1") {
alert("已有相同的模塊編碼");
}
});
});
});
</script>
9、 ASP.NET MVC中啟用CSS和JS文件捆綁優化:
使用BundleTable捆綁多個css文件和js文件,以提高網絡加載速度和頁面解析速度。
通過在Global.asax.cs文件中修改BundleTable的EnableOptimizations屬性來打開和關閉捆綁優化。
protected void Application_Start() { //other code has been removed for clarity //disable optimization System.Web.Optimization.BundleTable.EnableOptimizations = false; }
10、 ASP.NET MVC中有哪幾種方式去修改默認的layout
(1)、修改根目錄下的Views文件夾的 _ViewStart文件。_ViewStart為web application定義了默認layout頁面。可以通過代碼根據不同的Controller加載不同的layout。
@{
var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToSt ring(); string layout = ""; if (controller == "Admin") { layout = "~/Views/Shared/_AdminLayout.cshtml"; } else { layout = "~/Views/Shared/_Layout.cshtml"; } Layout = layout; }
(2)、在Views文件夾的某一個View目錄下新增 _ViewStart 文件。
(3)、在View頁面的頂部修改Layout
@{ Layout = "~/Views/Shared/_AdminLayout.cshtml"; }
(4)、在ActionResult中指定Layout
public ActionResult Index() { RegisterModel model = new RegisterModel(); //TO DO: return View("Index", "_AdminLayout", model); }
11、在ASP.NET MVC 中有三種方式從controller傳值到view中(還有一個實體模型傳值就不說了):
ViewData, ViewBag 和 TempData。Asp.net WebForm 中可以在一次用戶會話中使用Session去持久化數據。

ViewData
-
- ViewData 是一個繼承自
ViewDataDictionary
類的字典對象。public ViewDataDictionary ViewData { get; set; }
- ViewData 用來從controller中傳值到相對應的view中。
- 生命周期僅存在於當前此次請求。
- 如果發生重定向,那么值將會被清空。
- 從ViewData中取值時需要進行類型轉換和Null Check以避免異常。
- ViewData 是一個繼承自
ViewBag
-
- ViewBag ViewBag是一個動態屬性,是基於C# 4.0的動態語言的特性。
public Object ViewBag { get;}
- 是對ViewData的一次包裝,也是用來從controller中傳值到相對應的view中。
- 生命周期僅存在於當前此次請求。
- 如果發生重定向,那么值將會被清空。
- 從ViewBag中取值時不需要進行類型轉換。
- ViewBag ViewBag是一個動態屬性,是基於C# 4.0的動態語言的特性。
TempData
- TempData 是一個繼承於
TempDataDictionary
類的字典對象,存儲於Session中 。public TempDataDictionary TempData { get; set; }
- TempData 用來進行跨頁面請求傳值。
- TempData被請求后生命周期即結束。
- 從TempData中取值時需要進行類型轉換和Null Check以避免異常。
- 主要用來存儲一次性數據信息,比如error messages, validation messages。
詳情可參考:TempData知多少,
Session - ASP.NET MVC中Session是Controller中的一個屬性,Session是HttpSessionStateBase類型。
public HttpSessionStateBase Session { get; }
- Session保存數據直到用戶會話結束(默認session過期時間為20mins)。
- Session對所有的請求都有效,不僅僅是單一的跳轉。
- 從Session中取值時需要進行類型轉換和Null Check以避免異常。
12、數據注解(數據注釋)
Data Annotation 特性是位於System.ComponentModel.DataAnnotations
命名空間下,適用於Asp.net 項目(比如Asp.net web application & website, Asp.net MVC, Web forms ),同時也適用於Entity framework
ORM 模型。
Data Annotations幫助我們為model類或屬性定義規則進行數據驗證和顯示合適的提示信息給終端客戶。
Data Annotation 驗證特性:
- DataType - 為屬性指定數據類型
- DisplayName - 為屬性指定顯示名稱
- DisplayFormat - 為屬性指定顯示格式
- Required - 限制屬性為必錄
- ReqularExpression - 用正則表達式驗證屬性的值是否滿足要求
- Range - 限制屬性的值在某一區間
- StringLength - 指定string類型屬性的最小和最大長度
- MaxLength - 指定string類型屬性的最大長度
- Bind - 添加參數或表單數據到model屬性時,指定字段將會被添加到或排除
- ScaffoldColumn - 隱藏表單編輯界面的指定字段
ASP.NET MVC中如何注冊Area:
在使用Area之前,確保已經在Global.asax的Application_Start方法中注冊。
protected void Application_Start() { //Register all application Areas AreaRegistration.RegisterAllAreas(); }
需要記住的是,必須在最開始注冊Area,以至於注冊的settings, filters 和 routes
能夠應用於Area。
14、和 ASP.NET一樣, MVC Forms authentication在IIS認證完成之后發生。可以在 ASP.NET MVC應用程序中的Web.config文件的forms節點進行配置。
默認的表單認證配置如下:
<system.web>
<authentication mode="Forms"> <forms loginUrl="Login.aspx" protection="All" timeout="30" name=".ASPXAUTH" path="/" requireSSL="false" slidingExpiration="true" defaultUrl="default.aspx" cookieless="UseDeviceProfile" enableCrossAppRedirects="false" /> </authentication> </system.web>
15、
ASP.NET MVC如何允許輸入html tags:
ASP.NET MVC默認不允許用戶去提交html去避免Cross Site Scripting(CSS)攻擊 。ValidateInput
特性可以在action級別或controller級別啟用或禁用輸入校驗。
[ValidateInput(false)] public class HomeController : Controller { public ActionResult AddArticle() { return View(); } }
ValidateInput
特性對所有屬性都允許html tag輸入,但這是不安全的。 如果你只是想針對部分屬性允許html輸入,可以通過為屬性添加AllowHtml
特性。
public class BlogModel { [Required] [Display(Name = "Title")] public string Title { get; set; } [AllowHtml] [Required] [Display(Name = "Description")] public string Description { get; set; } }
16、MVC中設置緩存
//Action緩存,10秒
[OutputCache(Duration = 10)]
// GET: Home
public ActionResult Index()
{
ViewBag.CurrentTime = DateTime.Now;
return View();
}
public ActionResult Index2()
{
ViewBag.CurrentTime = DateTime.Now;
return View();
}
使用配置文件進行緩存配置
在MVC的Web.config文件中,可以對緩存進行相關的配置。
在system.web節點中,添加caching子節點,然后如下:
<outputCacheSettings> <outputCacheProfiles> <add name="TestConfigCache" duration="10" /> </outputCacheProfiles> </outputCacheSettings>
配置好后,我們的Control緩存或者Action緩存就可以這么寫:
[OutputCache(CacheProfile= "TestConfigCache")] // GET: Home public ActionResult Index() { ViewBag.CurrentTime = DateTime.Now; return View(); }