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

1.JQueryEasyUI使用

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

JQuery EasyUI中文官网下载地址:http://www.jeasyui.net/download/

jQuery EasyUI 1.4 版 API 中文版: 链接:http://pan.baidu.com/s/1c1pAutE%20 密码:0mk8

JQuery EasyUI 1.4.4 百度云盘:链接:http://pan.baidu.com/s/1bnRpH3T 密码:pbe9

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

 ASP.NET MVC+JQueryEasyUI1.4+ADO.NET Demo_第1张图片

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

  

 1.3:对于页面引用JQuery EasyUI那个css和js文件,参考如下:

 ASP.NET MVC+JQueryEasyUI1.4+ADO.NET Demo_第2张图片

 1.3.1:可以根据JQuery EasyUI Demo文件中具体引用的内容决定当前页面要引用的css和Js

 ASP.NET MVC+JQueryEasyUI1.4+ADO.NET Demo_第3张图片

1.3.2:使用chorme浏览器打开Demo/layout/basic.html,鼠标右键-->查看网页源代码

 ASP.NET MVC+JQueryEasyUI1.4+ADO.NET Demo_第4张图片

 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,返回新闻列表(使用数据库分页)

ASP.NET MVC+JQueryEasyUI1.4+ADO.NET Demo_第5张图片

ASP.NET MVC+JQueryEasyUI1.4+ADO.NET Demo_第6张图片

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:点击[删除]链接,弹出确认窗体

ASP.NET MVC+JQueryEasyUI1.4+ADO.NET Demo_第7张图片

6.2:点击[Ok],删除成功后,右下角显示删除成功提示信息

ASP.NET MVC+JQueryEasyUI1.4+ADO.NET Demo_第8张图片

7:点击[添加]链接,弹出模态dialog

7.1:使用kindeditor富文本编辑器:参考 ASP.NET 配置KindEditor文本编辑器

ASP.NET MVC+JQueryEasyUI1.4+ADO.NET Demo_第9张图片

页面添加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)]

ASP.NET MVC+JQueryEasyUI1.4+ADO.NET Demo_第10张图片

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,执行代码如下:

ASP.NET MVC+JQueryEasyUI1.4+ADO.NET Demo_第11张图片

2:判断当前Session["UserInfo"]==null,执行跳转代码,但是还会继续执行base.OnActionExecuting(filterContext);方法

ASP.NET MVC+JQueryEasyUI1.4+ADO.NET Demo_第12张图片

3:执行完BaseController中OnActionExecuting方法,则会继续执行HomeController控制器下的Index Action(按照我的理解不应该继续执行)

ASP.NET MVC+JQueryEasyUI1.4+ADO.NET Demo_第13张图片

ASP.NET MVC+JQueryEasyUI1.4+ADO.NET Demo_第14张图片

关于这点疑问,各位博友,有什么好的办法或者见解,帮我解惑一下,谢谢!

你可能感兴趣的:(ASP.NET MVC+JQueryEasyUI1.4+ADO.NET Demo)