ASP.NET MVC+JQueryEasyUI1.4+ADO.NET Demo

1.JQueryEasyUI使用javascript

JQuery EasyUI中文官網:http://www.jeasyui.net/css

JQuery EasyUI中文官網下載地址:http://www.jeasyui.net/download/html

jQuery EasyUI 1.4 版 API 中文版: 連接:http://pan.baidu.com/s/1c1pAutE%20 密碼:0mk8java

JQuery EasyUI 1.4.4 百度雲盤:連接:http://pan.baidu.com/s/1bnRpH3T 密碼:pbe9jquery

 1.1:把jquery.easyui.min.js和easyui-lang-zh_CN.js(1.4中是在locale文件夾下) 放到Scripts文件夾下web

 

 1.2:把themes文件夾下的css和icon放到Content/themes文件夾下ajax

  

 1.3:對於頁面引用JQuery EasyUI那個css和js文件,參考以下:數據庫

 

 1.3.1:能夠根據JQuery EasyUI Demo文件中具體引用的內容決定當前頁面要引用的css和Jsjson

 

1.3.2:使用chorme瀏覽器打開Demo/layout/basic.html,鼠標右鍵-->查看網頁源代碼跨域

 

 1.3.3:便可肯定當前頁面須要引用的css和jss

 

2:首先建立LoginControllers,而後添加Index視圖

 1 using DrHao.CMS.BLL;
 2 using DrHao.CMS.Model;
 3 using System;
 4 using System.Collections.Generic;
 5 using System.Linq;
 6 using System.Web;
 7 using System.Web.Mvc;
 8 
 9 namespace DrHao.CMS.WebApp.Controllers
10 {
11     public class LoginController : Controller
12     {
13         //
14         // GET: /Login/
15 
16         public ActionResult Index()
17         {
18             return View();
19         }
20         public ActionResult ProcessLogin()
21         {
22             string strUserName = Request["txtUserName"];
23             string strPwd = Request["txtPwd"];
24             UserInfoBLL userBll = new UserInfoBLL();
25             string strLoginSuccess = "ok:登陸成功,請稍等..";
26             string strLoginFaild = "no:用戶名或密碼錯誤,請檢查";
27             UserInfo userInfo = userBll.GetUserInfo(strUserName, strPwd);
28             Session.Add("UserInfo", userInfo);
29             string strReturn = userInfo != null ? strLoginSuccess : strLoginFaild;
30             return Content(strReturn);
31         }
32 
33     }
34 }
LoginControllers下的ProcessLogin方法
 1 @{
 2     Layout = null;
 3 }
 4 
 5 <!DOCTYPE html>
 6 
 7 <html>
 8 <head>
 9     <meta name="viewport" content="width=device-width" />
10     <title>Index</title>
11     <script src="~/Scripts/jquery-1.8.2.min.js"></script>
12     <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
13     <script>
14         function ajaxSuccess(data) {
15             //alert(data);
16             var strSplit = data.split(':');
17             if (strSplit[0]=='no') {
18                 $('#lbltxtMsg').text(strSplit[1]);
19             } else if(strSplit[0]=='ok') {
20                 //登陸成功
21                 $('#lbltxtMsg').text(strSplit[1]);
22                 window.location.href = '/Home/Index';
23             }
24             else {
25                 $("#lbltxtMsg").text('系統繁忙,請稍後再試...');
26             }
27         }
28     </script>
29 </head>
30 <body>
31     <div>
32         @using (Ajax.BeginForm("ProcessLogin", "Login", new AjaxOptions { HttpMethod = "post", LoadingElementId = "loading", OnSuccess = "ajaxSuccess" }))
33         {
34             <table>
35                 <tr>
36                     <td>用戶姓名:</td>
37                     <td>@Html.TextBox("txtUserName")</td>
38                 </tr>
39                 <tr>
40                     <td>用戶密碼:</td>
41                     <td>@Html.Password("txtPwd")</td>
42                 </tr>
43                 <tr>
44                     <td colspan="2">
45                         <input type="submit" name="AjaxSubmit" value="登錄" />
46                     </td>
47                 </tr>
48                 <tr>
49                     <td colspan="2">
50                         <label id="lbltxtMsg" style="color:red;"></label>
51                     </td>
52                 </tr>
53             </table>
54         }
55         <div id="loading" style="display:none;">
56             <img src="~/Content/04_ico_loading2.gif" />
57         </div>
58     </div>
59 </body>
60 </html>
LoginController Index視圖

使用到的ASP.NET MVC Ajax參考:Mvc4MicrosoftAjaxDemo

 3:登陸成功以後重定向到/Home/Index [使用JQueryEasyUI佈局 參考\demo\layout下的full.html]

 1 using DrHao.CMS.Model;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Web;
 6 using System.Web.Mvc;
 7 
 8 namespace DrHao.CMS.WebApp.Controllers
 9 {
10     public class HomeController : Controller
11     {
12         //
13         // GET: /Home/
14 
15         public ActionResult Index()
16         {
17             UserInfo user = Session["UserInfo"] as UserInfo;
18             if (user == null)
19             {
20                 return Redirect("/Login/Index");
21             }
22             else
23             {
24                 ViewBag.userLogin = user.UUserName;
25                 return View();
26             }
27         }
28 
29     }
30 }
HomeController下的Index方法
 1 @{
 2     Layout = null;
 3 }
 4 
 5 <!DOCTYPE html>
 6 
 7 <html>
 8 <head>
 9     <meta name="viewport" content="width=device-width" />
10     <title>Index</title>
11     <link href="~/Content/themes/default/easyui.css" rel="stylesheet" />
12     <link href="~/Content/themes/icon.css" rel="stylesheet" />
13     <link href="~/Content/themes/demo.css" rel="stylesheet" />
14     <script src="~/Scripts/jquery-1.8.2.min.js"></script>
15     <script src="~/Scripts/easyui-lang-zh_CN.js"></script>
16     <script src="~/Scripts/jquery.easyui.min.js"></script>
17     <script>
18         $(function () {
19             BindClickEvent();
20         });
21 
22         function BindClickEvent() {
23             $(".detailListLink").click(function () {
24                 var strText = $(this).text();
25                 var url = $(this).attr('Url');
26                 var isExist = $('#ttCenter').tabs('exists', strText);//判斷選項卡是否存在
27                 if (isExist) {
28                     $('#ttCenter').tabs('select', strText);
29                 } else {
30                     $('#ttCenter').tabs('add', {
31                         title: strText,
32                         content: ShowContent(url),
33                         closable: true
34                     });
35                 }
36             });
37         }
38 
39         function ShowContent(url) {
40             var strHtml = '<iframe src="' + url + '" scrolling="no" width="100%" height="100%" frameborder="0"></iframe>';
41             return strHtml;
42         }
43 
44     </script>
45 </head>
46 <body class="easyui-layout">
47     <!--頁面頂部設置開始-->
48     <div data-options="region:'north',border:false" style="height:60px;background:#B3DFDA;padding:10px">
49         <h1 style="text-align:center;">ASP.NET MVC4 Demo</h1>
50     </div>
51     <!--頁面頂部設置結束-->
52     <!--頁面左邊設置開始-->
53     <div data-options="region:'west',split:true,title:'West'" style="width:200px;padding:2px;">
54 
55         <!--左邊菜單欄設置開始-->
56         <div class="easyui-accordion" style="width:auto;height:200px;">
57             <div title="新聞管理" data-options="iconCls:'icon-ok'" style="overflow:auto;padding:10px;">
58                 <a href="Javascript:void(0)" class="detailListLink" url="/AdminNewList/Index">新聞管理</a>
59             </div>
60             <div title="評論管理" data-options="iconCls:'icon-help'" style="padding:10px;">
61                 <a href="Javascript:void(0)" class="detailListLink" url="/AdminCommentList/Index">評論管理</a>
62             </div>
63         </div>
64         <!--左邊菜單欄設置結束-->
65     </div>
66     <!--頁面左邊設置結束-->
67     <!--頁面中部設置開始-->
68     <div data-options="region:'center',title:'Center'" id="dvCenter">
69         <div class="easyui-tabs" style="width:700px;height:250px" fit="true" id="ttCenter">
70             <div title="首頁" style="padding:10px;overflow:hidden;">
71                 <h1>歡迎您:@ViewBag.userLogin<br/>
72                 當前時間:@DateTime.Now.ToString()
73                 </h1>
74             </div>
75 
76             @*<div title="首頁" style="padding:10px;overflow:hidden;">
77                     <iframe src="/AdminNewList/Index" scrolling="no" width="100%" height="100%" frameborder="0"></iframe>
78                 </div>*@
79         </div>
80 
81     </div>
82     <!--頁面中部設置結束-->
83     <!--頁面底部設置開始-->
84     <div data-options="region:'south',border:false" style="height:50px;background:#A9FACD;padding:10px;">
85         <h4 style="text-align:center;">Copyright &copy; Dr_Hao</h4>
86     </div>
87     <!--頁面底部設置結束-->
88 </body>
89 
90 </html>
HomeController Index視圖

顯示效果爲:

4:點擊左邊[新聞管理],請求/AdminNewList/Index,返回新聞列表(使用數據庫分頁)

MSSql分頁查詢語句參考:

select * from 
  (select row_number() over(order by id asc) as num,Id,Title,Msg,ImagePath,Author,SubDateTime from T_NewInfo) as T
   where T.num>=@start and T.num<=@end

PageBar.cs Common類 [根據pageIndex(當前頁面值)和PageCount(總的頁碼值)肯定]

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace DrHao.CMS.Common
 8 {
 9     public class PageBar
10     {
11         /// <summary>
12         /// 產生數字頁碼條
13         /// </summary>
14         /// <param name="pageIndex">當前頁碼值</param>
15         /// <param name="PageCount">總的頁碼值</param>
16         /// <returns></returns>
17         public static string GetPageBar(int pageIndex, int PageCount)
18         {
19             if (PageCount == 1)
20             {
21                 return string.Empty;
22             }
23 
24             int start = pageIndex - 5;//起始位置,要求頁面上顯示10個數字頁碼
25 
26             if (start < 1)
27             {
28                 start = 1;
29             }
30             int end = start + 9;//終止位置
31             if (end > PageCount)
32             {
33                 end = PageCount;
34             }
35             StringBuilder sbStr = new StringBuilder();
36             for (int i = start; i <= end; i++)
37             {
38                 if (i == pageIndex)
39                 {
40                     sbStr.Append(string.Format("<a href='javascript:void(0)' style='color:blue;font-weight: bold;'>{0}</a>", i));
41                 }
42                 else
43                 {
44                     sbStr.Append(string.Format("<a href='?pageIndex={0}'>{0}</a>", i));
45                 }
46             }
47             return sbStr.ToString();
48         }
49     }
50 }
PageBar.cs

TableStyle.css [用於設置table表格的樣式]

 1 table.gridtable {
 2     font-family: verdana,arial,sans-serif;
 3     font-size:11px;
 4     color:#333333;
 5     border-width: 1px;
 6     border-color: #666666;
 7     border-collapse: collapse;
 8 }
 9 table.gridtable th {
10     border-width: 1px;
11     padding: 8px;
12     border-style: solid;
13     border-color: #666666;
14     background-color: #dedede;
15 }
16 table.gridtable td {
17     border-width: 1px;
18     padding: 8px;
19     border-style: solid;
20     border-color: #666666;
21     background-color: #ffffff;
22 }
TableStyle.css

PageBar.css [用於設置分頁<a>標籤樣式]

 1 #Page {
 2     float: left;
 3     height: 50px;
 4     font-family: Verdana;
 5 }
 6 
 7     #Page a {
 8         float: left;
 9         margin: 10px 1px 0 1px;
10         width: 26px;
11         height: 20px;
12         line-height: 20px;
13         color: #91ad00;
14         font: 12px;
15         text-align: center;
16         text-decoration: none;
17         border: 1px solid #91ad00;
18     }
19 
20         #Page a:hover {
21             /*position: relative;*/
22             /*margin: 0 -10px 0 -10px;*/
23             /*padding: 0 1px;*/
24             /*width: 30px;*/
25             /*line-height: 40px;*/
26             /*height: 40px;*/
27             color: #000;
28             border: 1px solid #91ad00;
29             background: url() no-repeat left -10px;
30             font-size: 18px;
31             font-weight: bold;
32         }
33 
34     #Page span {
35         float: left;
36         line-height: 165%;
37         padding: 0px 8px;
38         margin: 10px 1px 0 1px;
39         border: 1px solid #91ad00;
40         background: #91ad00;
41         color: #FFF;
42         font-weight: bold;
43     }
PageBar.css

5:點擊[詳細]連接,彈出新聞管理詳細頁面[使用JQuery EasyUI \demo\dialog下的 toolbarbuttons.html]

5.1: 使用Ajax異步請求Controller的Action,返回Json數據到View

1  public ActionResult GetNewInfoModel()
2  {
3      int id = Convert.ToInt32(Request["id"]);
4      NewInfo newInfoModel = newinfoBll.GetUserInfoModel(id);
5      return Json(newInfoModel, JsonRequestBehavior.AllowGet);
6  }
Controller下Action GetNewInfoModel

5.2: View中使用Ajax請求Action

 1     $(function () {
 2 
 3         $("#dvDetails").css("display", "none");
 4         $("#divAdd").css("display","none");
 5 
 6         //顯示詳細內容
 7         $(".newInfoDetails").click(function () {
 8             ShowNewInfoDetail($(this).attr("dis"));
 9         });
10         //刪除信息
11         $(".newInfoDelete").click(function () {
12             DeleteNewInfo($(this).attr("dis"), this);
13         });
14         //修改信息
15         $(".newInfoUpdate").click(function () {
16             UpdateNewInfo($(this).attr("dis"));
17         });
18         //添加信息
19         $("#addInfo").click(function () {
20             AddNewInfo();
21         });
22     });
23 
24     //顯示詳細信息
25     function ShowNewInfoDetail(id) {
26         $.post("/AdminNewList/GetNewInfoModel", { "id": id }, function (data) {
27             $("#title").text(data.Title);
28             $("#author").text(data.Author);
29             $("#subDateTime").text(ChangeDataFormat(data.SubDateTime));
30             $("#msg").text(data.Msg);
31         }, "json");
32 
33         $("#dvDetails").css("display", "block");
34 
35         $('#dvDetails').dialog({
36             title: '詳細內容',
37             width: 400,
38             height: 300,
39             closed: false,
40             cache: false,
41             collapsible: true,
42             minimizable: true,
43             maximizable: true,
44             modal: true,
45             buttons: [{
46                 text: 'Ok',
47                 iconCls: 'icon-ok',
48                 handler: function () {
49                     alert('ok');
50                 }
51             }, {
52                 text: 'Cancel',
53                 handler: function () {
54                     $('#dvDetails').dialog('close');
55                 }
56             }]
57         });
58     }
Index.cshtml Page JavaScript

 Ps: Action返回Json數據,DateTime類型會返回爲毫秒數,須要使用如下方法進行處理ChangeDataFormat(cellval)

1 function ChangeDataFormat(cellval) {
2     var data = new Date(parseInt(cellval.replace("/Date(", "").replace(")/", ""), 10));
3     var month = data.getMonth() + 1 < 10 ? "0" + (data.getMonth() + 1) : data.getMonth() + 1;
4     var currentDate = data.getDate() < 10 ? "0" + data.getDate() : data.getDate();
5     return data.getFullYear() + "-" + month + "-" + currentDate;
6 }
ChangeDataFormat(cellval) function

6:點擊[刪除]連接,彈出confirm確認信息頁面,使用JQuery.post Ajax,成功刪除後,右下角顯示成功刪除提示信息

   [使用JQuery EasyUI \demo\messager下的interactive.html和basic.html]

6.1:點擊[刪除]連接,彈出確認窗體

6.2:點擊[Ok],刪除成功後,右下角顯示刪除成功提示信息

7:點擊[添加]連接,彈出模態dialog

7.1:使用kindeditor富文本編輯器:參考 ASP.NET 配置KindEditor文本編輯器

頁面添加kindeditor css和js的引用

    <link href="~/kindeditor/themes/default/default.css" rel="stylesheet" />
    <link href="~/kindeditor/plugins/code/prettify.css" rel="stylesheet" />
    <script src="~/kindeditor/plugins/code/prettify.js"></script>
    <script src="~/kindeditor/kindeditor.js"></script>
    <script src="~/kindeditor/lang/zh_CN.js"></script>
    <link href="~/Content/themes/TableStyle.css" rel="stylesheet" />
    <script>
        KindEditor.ready(function (K) {
            var editor1 = K.create('#MsgContent', {
                uploadJson: 'kindeditor/asp.net/upload_json.ashx',
                //文件管理
                fileManagerJson: 'kindeditor/asp.net/file_manager_json.ashx',
                allowFileManager: true,
                //設置編輯器建立後執行的回調函數
                afterBlur: function () { this.sync(); },//異步提交時須要
                afterCreate: function () {
                    var self = this;
                    self.sync();//把富文本編輯器的內容放到文本域中
                }
            });
            prettyPrint();//要調用該方法
        });
    </script>
<textarea id="MsgContent" cols="100" rows="8" style="width:400px;height:250px;visibility:hidden;" name="Msg"></textarea>

7.2:異步上傳圖片 MyAjaxForm.js  基於 ASP.NET MVC Microsoft Ajax 參考地址:http://www.cnblogs.com/Dr-Hao/p/5206575.html

MyAjaxForm.js 下載地址:http://jquery.malsup.com/form/

MyAjaxForm.js 百度雲盤:連接:http://pan.baidu.com/s/1gekKOgj  密碼:83ud

jQueryFormPlugin參考文檔[html]百度雲盤:連接:http://pan.baidu.com/s/1hrxAby8  密碼:ph56

頁面添加js引用:

<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/MyAjaxForm.js"></script>
$("#form1").ajaxSubmit({
     type: "post",
     url: "url",
     success: function (data) {
        //server data
     }
 });

7.3:父窗體調用子窗體方法

//調用子窗體中的方法
var childWindow = $("")[0].contentWindow; //轉換爲dom對象 獲取子窗體對象
childWindow.subForm(); //subForm 是子窗體方法

    子窗體調用父窗體的方法

//添加完成之後,調用該方法,關閉添加的窗口
//調用父窗體AfterAdd方法
function AfterAdd() {
    window.parent.AfterAdd();
}

7.4:容許富文本編輯器提交HTML

1:Controller中Action標記爲 [ValidateInput(false)]

2:web.config 中httpRuntime 添加requestValidationMode="2.0"

 

父窗體Index.cshtml源代碼:

  1 @{
  2     Layout = null;
  3 }
  4 @using DrHao.CMS.Model
  5 @using DrHao.CMS.Common
  6 <!DOCTYPE html>
  7 <html>
  8 <head>
  9     <meta name="viewport" content="width=device-width" />
 10     <title>Index</title>
 11     <link href="~/Content/themes/PageBar.css" rel="stylesheet" />
 12     <link href="~/Content/themes/TableStyle.css" rel="stylesheet" />
 13     <link href="~/Content/themes/default/easyui.css" rel="stylesheet" />
 14     <link href="~/Content/themes/icon.css" rel="stylesheet" />
 15     <link href="~/Content/themes/demo.css" rel="stylesheet" />
 16     <script src="~/Scripts/jquery-1.8.2.min.js"></script>
 17     <script src="~/Scripts/easyui-lang-zh_CN.js"></script>
 18     <script src="~/Scripts/jquery.easyui.min.js"></script>
 19     <script>
 20         $(function () {
 21 
 22             $("#dvDetails").css("display", "none");
 23             $("#divAdd").css("display", "none");
 24 
 25             //顯示詳細內容
 26             $(".newInfoDetails").click(function () {
 27                 ShowNewInfoDetail($(this).attr("dis"));
 28             });
 29             //刪除信息
 30             $(".newInfoDelete").click(function () {
 31                 DeleteNewInfo($(this).attr("dis"), this);
 32             });
 33             //修改信息
 34             $(".newInfoUpdate").click(function () {
 35                 UpdateNewInfo($(this).attr("dis"));
 36             });
 37             //添加信息
 38             $("#addInfo").click(function () {
 39                 AddNewInfo();
 40             });
 41         });
 42 
 43         //顯示詳細信息
 44         function ShowNewInfoDetail(id) {
 45             $.post("/AdminNewList/GetNewInfoModel", { "id": id }, function (data) {
 46                 $("#title").text(data.Title);
 47                 $("#author").text(data.Author);
 48                 $("#subDateTime").text(ChangeDataFormat(data.SubDateTime));
 49                 $("#msg").html(data.Msg);
 50             }, "json");
 51 
 52             //$.get("/AdminNewList/GetNewInfoModel", { "id": id }, function (data) {
 53             //    $("#title").text(data.Title);
 54             //    $("#author").text(data.Author);
 55             //    $("#subDateTime").text(data.SubDateTime);
 56             //    $("#msg").text(data.Msg);
 57             //}, "json");
 58 
 59             ////原本還覺得是ajax跨域問題,使用jsonp來解決,請求沒有跨域
 60             //$.ajax({
 61             //    type: "get",
 62             //    async: false,
 63             //    url: "/AdminNewList/GetNewInfoModel",
 64             //    data: { "id": id },
 65             //    dataType: "json",
 66             //    //jsonp: "callback",//傳遞給請求處理程序或頁面的,用以得到jsonp回調函數名的參數名(通常默認爲:callback)
 67             //    //jsonpCallback: "?",//自定義的jsonp回調函數名稱,默認爲jQuery自動生成的隨機函數名,也能夠寫"?",jQuery會自動爲你處理數據
 68             //    success: function (json) {
 69             //        $("#title").text(json.Title);
 70             //        $("#author").text(json.Author);
 71             //        $("#subDateTime").text(json.SubDateTime);
 72             //        $("#msg").text(json.Msg);
 73             //    },
 74             //    error: function () {
 75             //        alert('fail');
 76             //    }
 77             //});
 78 
 79             $("#dvDetails").css("display", "block");
 80 
 81             $('#dvDetails').dialog({
 82                 title: '詳細內容',
 83                 width: 400,
 84                 height: 300,
 85                 closed: false,
 86                 cache: false,
 87                 collapsible: true,
 88                 minimizable: true,
 89                 maximizable: true,
 90                 modal: true,
 91                 buttons: [{
 92                     text: 'Ok',
 93                     iconCls: 'icon-ok',
 94                     handler: function () {
 95                         alert('ok');
 96                     }
 97                 }, {
 98                     text: 'Cancel',
 99                     handler: function () {
100                         $('#dvDetails').dialog('close');
101                     }
102                 }]
103             });
104         }
105 
106         function ChangeDataFormat(cellval) {
107             var data = new Date(parseInt(cellval.replace("/Date(", "").replace(")/", ""), 10));
108             var month = data.getMonth() + 1 < 10 ? "0" + (data.getMonth() + 1) : data.getMonth() + 1;
109             var currentDate = data.getDate() < 10 ? "0" + data.getDate() : data.getDate();
110             return data.getFullYear() + "-" + month + "-" + currentDate;
111         }
112 
113         //刪除NewInfo記錄
114         function DeleteNewInfo(id, control) {
115             $.messager.confirm("提示", "你肯定要刪除這條記錄嗎?", function (data) {
116                 if (data) {
117                     $.post("/AdminNewList/DeleteNewInfo", { "id": id }, function (data) {
118                         if (data == "ok") {
119                             //肯定刪除
120                             $.messager.show({
121                                 title: '提示',
122                                 msg: '你已經成功刪除Id爲:' + id + " 的數據",
123                                 timeout: 4000,
124                                 showType: 'slide'
125                             });
126 
127                             //刪除頁面的信息
128                             $(control).parent().parent().remove();
129                         }
130                     });
131                 }
132             });
133         }
134 
135         //修改NewInfo信息
136         function UpdateNewInfo(id) {
137 
138         }
139 
140         //添加NewInfo信息
141         function AddNewInfo() {
142             $("#AddFrame").attr("src", "/AdminNewList/ShowAddInfo");
143 
144             $('#divAdd').dialog({
145                 title: '添加新聞',
146                 top: 50,
147                 left: 200,
148                 width: 750,
149                 height: 500,
150                 closed: false,
151                 cache: false,
152                 collapsible: true,
153                 minimizable: true,
154                 maximizable: true,
155                 modal: true,
156                 buttons: [{
157                     text: 'Ok',
158                     iconCls: 'icon-ok',
159                     handler: function () {
160                         //調用子窗體中的方法
161                         var childWindow = $("#AddFrame")[0].contentWindow;//獲取子窗體的window對象
162                         childWindow.subForm();
163                     }
164                 }, {
165                     text: 'Cancel',
166                     handler: function () {
167                         $('#divAdd').dialog('close');
168                     }
169                 }]
170             });
171 
172             $("#divAdd").css("display", "block");
173         }
174 
175         //添加完成之後,調用該方法關閉添加窗口
176         function AfterAdd() {
177             $('#divAdd').dialog('close');
178         }
179     </script>
180 </head>
181 <body>
182     <div>
183         <a href="javascript:void(0)" id="addInfo">添加</a>
184         @if (ViewData["liNewInfo"] != null)
185         {
186             <table class="gridtable">
187                 <tr>
188                     <th>編號</th>
189                     <th>標題</th>
190                     <th>做者</th>
191                     <th>時間</th>
192                     <th>詳細</th>
193                     <th>刪除</th>
194                     <th>修改</th>
195                 </tr>
196                 @foreach (NewInfo newInfo in (List<NewInfo>)ViewData["liNewInfo"])
197                 {
198                     <tr>
199                         <td>@newInfo.Id</td>
200                         <td>@newInfo.Title</td>
201                         <td>@newInfo.Author</td>
202                         <td>@newInfo.SubDateTime</td>
203                         <td><a href="javascript:void(0)" class="newInfoDetails" dis="@newInfo.Id">詳細</a></td>
204                         <td><a href="javascrpit:void(0)" class="newInfoDelete" dis="@newInfo.Id">刪除</a></td>
205                         <td><a href="javascrpit:void(0)" class="newInfoUpdate" dis="@newInfo.Id">修改</a></td>
206                     </tr>
207                 }
208             </table>
209             <div id="Page">
210                 @Html.Raw(
211                  @PageBar.GetPageBar(Convert.ToInt32(ViewData["pageIndex"]), Convert.ToInt32(ViewData["pageCount"])))
212             </div>
213         }
214         else
215         {
216             <span>暫無數據</span>
217         }
218 
219         <!--詳細內容開始-->
220         <div id="dvDetails">
221             <table class="gridtable">
222                 <tr>
223                     <td>標題</td>
224                     <td><span id="title"></span></td>
225                 </tr>
226                 <tr>
227                     <td>做者</td>
228                     <td><span id="author"></span></td>
229                 </tr>
230                 <tr>
231                     <td>時間</td>
232                     <td><span id="subDateTime"></span></td>
233                 </tr>
234                 <tr>
235                     <td>詳細內容</td>
236                     <td><span id="msg"></span></td>
237                 </tr>
238             </table>
239         </div>
240         <!--詳細內容結束-->
241         <!--添加信息內容開始-->
242         <div id="divAdd" style="overflow:hidden;">
243             <iframe id="AddFrame" frameborder="0" width="100%" height="100%" scrolling="auto"> </iframe>
244         </div>
245         <!--添加信息內容結束-->
246         <!---修改內容開始-->
247         <!---修改內容結束-->
248 
249     </div>
250 </body>
251 </html>
Index.cshtml

子窗體ShowAddInfo.cshtml源代碼:

  1 @{
  2     Layout = null;
  3 }
  4 
  5 <!DOCTYPE html>
  6 
  7 <html>
  8 <head>
  9     <meta name="viewport" content="width=device-width" />
 10     <title>添加新聞</title>
 11     <link href="~/kindeditor/themes/default/default.css" rel="stylesheet" />
 12     <link href="~/kindeditor/plugins/code/prettify.css" rel="stylesheet" />
 13     <script src="~/kindeditor/plugins/code/prettify.js"></script>
 14     <script src="~/kindeditor/kindeditor.js"></script>
 15     <script src="~/kindeditor/lang/zh_CN.js"></script>
 16     <link href="~/Content/themes/TableStyle.css" rel="stylesheet" />
 17 
 18     <script src="~/Scripts/jquery-1.8.2.min.js"></script>
 19     <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
 20     <script src="~/Scripts/MyAjaxForm.js"></script>
 21 
 22     <script src="~/Scripts/jquery.easyui.min.js"></script>
 23     <script src="~/Scripts/easyui-lang-zh_CN.js"></script>
 24     <script>
 25         KindEditor.ready(function (K) {
 26             var editor1 = K.create('#MsgContent', {
 27                 uploadJson: 'kindeditor/asp.net/upload_json.ashx',
 28                 //文件管理
 29                 fileManagerJson: 'kindeditor/asp.net/file_manager_json.ashx',
 30                 allowFileManager: true,
 31                 //設置編輯器建立後執行的回調函數
 32                 afterBlur: function () { this.sync(); },//異步提交時須要
 33                 afterCreate: function () {
 34                     var self = this;
 35                     self.sync();//把富文本編輯器的內容放到文本域中
 36                 }
 37             });
 38             prettyPrint();//要調用該方法
 39         });
 40 
 41         $(function () {
 42             FileUpload();
 43         });
 44 
 45         function FileUpload() {
 46             $("#btnFileUp").click(function () {
 47                 if ($("#fileUpImage").val() == "") {
 48                     $.messager.alert("提示", "請選擇上傳的文件圖片", "info");
 49                     return;
 50                 }
 51 
 52                 $("#form1").ajaxSubmit({
 53                     type: "post",
 54                     url: "/AdminNewList/FileUpload",
 55                     success: function (data) {
 56                         var serverData = data.split(":");
 57                         if (serverData[0] == "ok") {
 58                             $("#showImage").append("<img src='" + serverData[1] + "'width='40px' height='40px'/>");
 59                             $("#hidImagePath").val(serverData[1]);//將路徑賦值給隱藏域,提交表單時將提交給服務端保存到數據庫
 60                             $("#txtMsg").text();
 61                         } else if (serverData[0] == "no") {
 62                             $("#txtMsg").text(serverData[1]);
 63                         } else {
 64                             $("#txtMsg").text('系統繁忙,請稍後再試...');
 65                         }
 66                     }
 67                 });
 68             });
 69         }
 70 
 71         //提交表單
 72         function subForm() {
 73             $("#form1").submit();
 74         }
 75 
 76         //添加完成之後,調用該方法,關閉添加的窗口
 77         //調用父窗體AfterAdd方法
 78         function AfterAdd() {
 79             window.parent.AfterAdd();
 80         }
 81     </script>
 82 </head>
 83 <body>
 84     <div>
 85         @using (Ajax.BeginForm("AddNewInfo", "AdminNewList", new AjaxOptions() { HttpMethod = "post", OnSuccess = "AfterAdd" }, new { id = "form1" }))
 86         {
 87             <table class="gridtable">
 88                 <tr>
 89                     <td>新聞標題</td>
 90                     <td><input type="text" name="Title" value=" " /></td>
 91                 </tr>
 92                 <tr>
 93                     <td>做者</td>
 94                     <td><input type="text" name="Author" value=" " /></td>
 95                 </tr>
 96                 <tr>
 97                     <td>上傳圖片</td>
 98                     <td>
 99                         <input type="file" name="fileUp" id="fileUpImage" />
100                         <input type="submit" value="上傳圖片" id="btnFileUp" />
101                         <input type="hidden" name="ImagePath" value="hidImagePath" />
102                         <div id="showImage"></div>
103                         <span id="txtMsg" style="color:red;"></span>
104                     </td>
105                 </tr>
106                 <tr>
107                     <td>新聞內容</td>
108                     <td>
109                         <textarea id="MsgContent" cols="100" rows="8" style="width:400px;height:250px;visibility:hidden;" name="Msg"></textarea>
110                     </td>
111                 </tr>
112             </table>
113         }
114     </div>
115 </body>
116 </html>
ShowAddInfo.cshtml

控制器AdminNewListController.cs源代碼:

 1 using DrHao.CMS.Model;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.IO;
 5 using System.Linq;
 6 using System.Web;
 7 using System.Web.Mvc;
 8 
 9 namespace DrHao.CMS.WebApp.Controllers
10 {
11     public class AdminNewListController : BaseController
12     {
13         //
14         // GET: /AdminNewList/
15         BLL.NewInfoBLL newinfoBll = new BLL.NewInfoBLL();
16         public ActionResult Index()
17         {
18             int pageIndex = Request["pageIndex"] != null ? Convert.ToInt32(Request["pageIndex"]) : 1;
19             int pageSize = 5;
20             int pageCount = newinfoBll.GetPageCount(pageSize);
21             pageIndex = pageIndex < 1 ? 1 : pageIndex;
22             pageIndex = pageIndex > pageCount ? pageCount : pageIndex;
23 
24             List<NewInfo> liNewInfo = newinfoBll.GetPageList(pageIndex, pageSize);//得到分頁數據
25 
26             ViewData["liNewInfo"] = liNewInfo;
27             ViewData["pageIndex"] = pageIndex;
28             ViewData["pageCount"] = pageCount;
29             return View();
30         }
31 
32         public ActionResult GetNewInfoModel()
33         {
34             int id = Convert.ToInt32(Request["id"]);
35             NewInfo newInfoModel = newinfoBll.GetUserInfoModel(id);
36             return Json(newInfoModel, JsonRequestBehavior.AllowGet);
37         }
38 
39         public ActionResult DeleteNewInfo()
40         {
41             int id = Convert.ToInt32(Request["id"]);
42             int result = newinfoBll.DeleteNewInfo(id);
43 
44             return Content(result > 0 ? "ok" : "no");
45         }
46 
47         public ActionResult ShowAddInfo()
48         {
49             return View();
50         }
51 
52         public ActionResult FileUpload()
53         {
54             HttpPostedFileBase postFile = Request.Files["fileUp"];
55             if (postFile == null)
56             {
57                 return Content("no:請選擇上傳文件");
58             }
59             else
60             {
61                 string fileName = Path.GetFileName(postFile.FileName);//文件名
62                 string fileExt = Path.GetExtension(fileName);//文件的擴展名
63                 if (fileExt == ".jpg")
64                 {
65                     string dir = "/attached/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/";
66                     Directory.CreateDirectory(Path.GetDirectoryName(Request.MapPath(dir)));//建立文件夾
67 
68                     string newFileName = Guid.NewGuid().ToString();//新的文件名
69                     string fulDir = dir + newFileName + fileExt;
70                     postFile.SaveAs(Request.MapPath(fulDir));
71                     return Content("ok:" + fulDir);
72                 }
73                 else
74                 {
75                     return Content("no:文件格式錯誤");
76                 }
77             }
78         }
79 
80         [ValidateInput(false)]
81         public ActionResult AddNewInfo(NewInfo newinfo)
82         {
83             newinfo.SubDateTime = DateTime.Now;
84             return newinfoBll.AddInfo(newinfo) ? Content("ok") : Content("no");
85         }
86 
87     }
88 }
AdminNewListController.cs

DrHao.CMS總體參考源代碼:連接:http://pan.baidu.com/s/1jHfpkmM%20 密碼:f2t8

MVCBlog(ASP.NET MVC 4.0+EF 簡單Demo) 連接:http://pan.baidu.com/s/1bkVvcU  密碼:1c2f

Q:我在DrHao.CMS中定義一個BaseController控制器,代碼以下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6 using System.Web.Providers.Entities;
 7 
 8 namespace DrHao.CMS.WebApp.Controllers
 9 {
10     public class BaseController : Controller
11     {
12         //
13         // GET: /Base/
14         protected override void OnActionExecuting(ActionExecutingContext filterContext)
15         {
16             if (Session["UserInfo"]==null)
17             {
18                 //沒效果,仍是會執行Action的方法
19                 filterContext.HttpContext.Response.Redirect("/Login/Index");
20             }
21             base.OnActionExecuting(filterContext);
22         }
23 
24     }
25 }
BaseController .cs

運行DrHao.CMS 直接訪問 /Home/Index ,HomeController繼承BaseController 代碼以下:

 1 using DrHao.CMS.Model;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Web;
 6 using System.Web.Mvc;
 7 
 8 namespace DrHao.CMS.WebApp.Controllers
 9 {
10     public class HomeController : BaseController
11     {
12         //
13         // GET: /Home/
14 
15         public ActionResult Index()
16         {
17             UserInfo user = Session["UserInfo"] as UserInfo;
18             //user判斷 正常狀況下不須要寫
19             if (user == null)
20             {
21                 return Redirect("/Login/Index");
22             }
23             else
24             {
25                 ViewBag.userLogin = user.UUserName;
26                 return View();
27             }
28 
29         }
30 
31     }
32 }
HomeController.cs

正常狀況下,在沒有登錄當前用戶的時候,直接訪問/Home/Index,會執行BaseController中的 protected override void OnActionExecuting(ActionExecutingContext filterContext)方法,判斷當前用戶沒有登錄,則直接跳轉,不會執行/Home/Index Action中的方法,但實際運行效果,會繼續執行/Home/Index中的方法(若在/Home/Index中不加入判斷,則直接拋出異常信息,user不能爲null)

 1:直接訪問/Home/Index View,執行代碼以下:

2:判斷當前Session["UserInfo"]==null,執行跳轉代碼,可是還會繼續執行base.OnActionExecuting(filterContext);方法

3:執行完BaseController中OnActionExecuting方法,則會繼續執行HomeController控制器下的Index Action(按照個人理解不該該繼續執行)

關於這點疑問,解決方案:

filterContext.HttpContext.Response.Redirect("/Login/Index");

是瀏覽器端的跳轉,執行完上面代碼,會繼續往下執行Action,直到發生錯誤(錯誤信息客戶端看不到),而後執行客戶端跳轉(不推薦)

filterContext.Result = new RedirectResult("/Login/Index");

是服務器端的跳轉,後續Action都不會執行(推薦)

相關文章
相關標籤/搜索