MVC

继续 mvc-11(上).dto:http://www.cnblogs.com/tangge/p/3840060.html

jquery.tmpl.js 下载:http://pan.baidu.com/s/1o68w7Ke

jquery.tmpl.js 接收JSON类型数据循环

1.tmpl.js 前台显示数据

前台

Index.cshtml

Index.cshtml
Index.cshtml

@{
    ViewBag.Title = "学员列表";
}
@section headSection{
<script type="text/x-jquery-tmpl" id="trtemp">
        <tr>
            <th>${StudentID}</th>
            <th>${Cid}</th>
            <th>${Name}</th>
            <th>${Gender}</th>
            <th>操作</th>
        </tr>
    </script>

    <script type="text/javascript">
        $(function () {
            //0.关闭Jquery的浏览器缓存
            $.ajaxSetup({ cache: false });
            loadPageList(1);
        });
        
        //根据页码 异步请求数据
        function loadPageList(pageIndex) {
            $.get("/Stu/List/" + pageIndex, null, function (jsonData) {
                if (jsonData.Statu=="OK") {
                    //alert(jsonData.Msg);
                    $("#trtemp").tmpl(jsonData.Data.PageData).appendTo("#tableList");
                }
                alert(jsonData.msg);
            },"json");
        }
    </script>
}
<table id="tableList" border="1" cellspacing="0" cellpadding="0" width="100%">
    <tr>
        <th>ID</th>
        <th>班级名</th>
        <th>姓名</th>
        <th>性别</th>
        <th>操作</th>       
    </tr>
</table>

但是要报错

TypeError: $(...).tmpl is not a function

$("#trtemp").tmpl(jsonData.Data.PageData).appendTo("#tableList");

image

找了半天原因,结果查看页面源代码

image

这里,在_Layout.cshtml里面,引入juqey和tmpl,然后注释调

@Scripts.Render("~/bundles/jquery")

image

2.ajax分页

PageBar.js (C#类库)

下载地址:http://pan.baidu.com/s/1gdsvLRX 密码:jtou

导入PageBar.js  ( 最好导入_ViewStart.cshtml )

<script type="text/javascript" src="~/Scripts/PageBar.js"></script>

_ViewStart.cshtml 加一个样式

@Styles.Render("~/Content/BarStyle.css")

BarStyle.css

BarStyle.css
BarStyle.css

#PageBar
{
    margin: 10px auto;
    width: 550px;
    text-align: center;
    border: 1px solid #808080;
}

    #PageBar a
    {
        padding: 2px 4px;
        margin: 4px;
        border: 1px solid #000000;
        background-color: #606fc2;
        line-height: 32px;
        color: #ffffff;
        cursor: pointer;
    }

     #PageBar a:hover {
         background-color: orange;
     }

//生成页码条方法(翻页方法名,页码条容器(div),当前页码,总页数,页码组容量,总行数)

makePageBar(jsMethodName,pageContainer, pgIndex, pgCount, gpSize, roCount)

Index.cshtml

Index.cshtml
Index.cshtml

@{
    ViewBag.Title = "学员列表";
}
@section headSection{
<style type="text/css">
    #tableList tr td {
        text-align: center;
    }
    </style>
    <script type="text/x-jquery-tmpl" id="trtemp">
        <tr>
            <td>${StudentID}</td>
            <td>${Class.CName}</td>
            <td>${Name}</td>
            <td>${Gender}</td>
            <td>操作</td>
        </tr>
    </script>

    <script type="text/javascript">
        $(function () {
            //0.关闭Jquery的浏览器缓存
            $.ajaxSetup({ cache: false });
            loadPageList(1);
        });

        //根据页码 异步请求数据
        function loadPageList(pageIndex) {
            $.get("/Stu/List/" + pageIndex, null, function (jsonData) {
                if (jsonData.Statu == "OK") {
                    //alert(jsonData.Msg);
                    $("#tableList tr td").remove();
                    $("#trtemp").tmpl(jsonData.Data.PageData).appendTo("#tableList");
                }
                //生成页码条方法(翻页方法名,页码条容器(div),当前页码,总页数,页码组容量,总行数)
                makePageBar(
                    loadPageList,
                    document.getElementById("PageBar"),
                    jsonData.Data.PageIndex,//当前页码
                    jsonData.Data.PageCount,//总页数
                    2,//页码组容量
                    jsonData.Data.RowCount);//总行数
                //alert(jsonData.msg);
            }, "json");
        }
    </script>

}
<table id="tableList" border="1" cellspacing="0" cellpadding="0" width="100%">
    <tr>
        <th>ID</th>
        <th>班级名</th>
        <th>姓名</th>
        <th>性别</th>
        <th>操作</th>
    </tr>
</table>
<

div id="PageBar"></div

>

如图

image

3.msgBox.js 窗口
Shared/_Layout.cshtml

<script type="text/javascript">
        $(function () {
            $.msgBox = new MsgBox({ "imghref": "/images/" });
        })
      
    </script>

一般的方法

$.msgBox.showMsgOk(“更新成功!”);

4.显示修改面板

4.1.修改tmpl模版,增加操作项

<style type="text/css">
        #tableList tr td {
            text-align: center;
        }

        #tbData {
            margin: 0 auto;
            width: 500px;
            display: none;
        }
    </style>
    <script type="text/x-jquery-tmpl" id="trtemp">
        <tr>
            <td>${StudentID}</td>
            <td>${Class.CName}</td>
            <td>${Name}</td>
            <td>${Gender}</td>
            <td>
                <a href="javascript:DoDel(${StudentID})"></a>
                <a href="javascript:void(0)" onclick="Modify(${StudentID},this)"></a>
</td>
        </tr>
    </script>

4.2. 传值jquery

Index.cshtml 显示修改面板jquery
Index.cshtml 显示修改面板jquery

//显示修改面板
        function Modify(id,obJec) {
            console.info(id,obJec)
            $.getJSON("/Stu/Get/",{"id":id},function (jsonObj) {
                $("#tbData").css("display","block");

                //判断返回的Statu
                if (jsonObj.Statu =="OK") {
                    //console.info(jsonObj.Data.Name)
                    $("#StudentID").val(jsonObj.Data.StudentID)
                    $("#Name").val(jsonObj.Data.Name);
                    $("#Cid").val(jsonObj.Data.Cid);//班级
                    //性别
                    if (jsonObj.Data.Gender=="男") {
                        $("#GenderFF").removeAttr("Checked");
                        $("#GenderW").removeAttr("Checked");
                        $("#GenderM").attr("Checked","Checked");
                    }else if (jsonObj.Data.Gender=="女") {
                        $("#GenderFF").removeAttr("Checked");
                        $("#GenderM").removeAttr("Checked");
                        $("#GenderW").attr("Checked","Checked");
                    }else {
                        $("#GenderM").removeAttr("Checked");
                        $("#GenderW").removeAttr("Checked");
                        $("#GenderFF").attr("Checked","Checked");
                    }
                }
            })
        }

4.3.添加修改面板html

index.chtml 添加修改面板html
index.chtml 添加修改面板html

@*修改面板*@
<table id="tbData" border="1">
    <tr>
        <td>姓名</td>
        <td>
            <input type="text" id="Name" name="Name" />
        </td>
    </tr>
    <tr>
        <td>班级</td>
        <td>
            @Html.DropDownList("Cid", ViewBag.seList as IEnumerable<SelectListItem>)
        </td>
    </tr>
    <tr>
        <td>性别</td>
        <td>
            <input type="radio" id="GenderFF" name="Gender" value="保密" checked="checked" />保密
            <input type="radio" id="GenderM" name="Gender" value="男" /><input type="radio" id="GenderW" name="Gender" value="女" /></td>
    </tr>
    <tr>
        <td>
            <input type="button" id="btnSure" value="提 交" />
        </td>
        <td>
            <input type="button" id="btnCansole" value="取 消" />
        </td>
    </tr>
</table>

4.4.后台:StuController.cs

先加载班级,Get方法是根据id查询学员数据(显示修改数据)

StuController.cs
StuController.cs

public ActionResult Index()
        {
            //1.0查询班级数据
            List<Models.Class> list = db.Classes.Where(s => s.CIsdel == "0").ToList();
            //1.1 将班级数据封装到SelectList,并指定Value和Text
            SelectList seList = new SelectList(list, "Cid", "CName");
            //1.2 调用 SelectList 的 AsEnumerable 自动生成 SelectListItem 并存入 ViewBag
            ViewBag.seList = seList.AsEnumerable();
            return View();
        }

        /// <summary>
        /// 3.1 根据id查询学员数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Get(int id)
        {
            //根据id查询
            Models.Student model = db.Students.Where(s => s.StudentID == id).FirstOrDefault();
            Models.JsonModel jsonModle = new Models.JsonModel()
            {
                Data = model.ToDto(),
                Msg = "成功",
                Statu = "OK"
            };
            return Json(jsonModle, JsonRequestBehavior.AllowGet);
        }
1

5.实现修改方法

5.1.添加form表单

Index.cshtml 添加form表单html部分
Index.cshtml 添加form表单html部分

@*修改面板*@
<form id="tFormData">
    <table id="tbData" border="1">
        <tr>
            <td>姓名<input type="hidden" id="StudentID" name="StudentID" /></td>
            <td>
                <input type="text" id="Name" name="Name" />
            </td>
        </tr>
        <tr>
            <td>班级</td>
            <td>
                @Html.DropDownList("Cid", ViewBag.seList as IEnumerable<SelectListItem>)
            </td>
        </tr>
        <tr>
            <td>性别</td>
            <td>
                <input type="radio" id="GenderFF" name="Gender" value="保密" checked="checked" />保密
                <input type="radio" id="GenderM" name="Gender" value="男" /><input type="radio" id="GenderW" name="Gender" value="女" /></td>
        </tr>
        <tr>
            <td>
                <input type="button" id="btnSure" value="提 交" />
            </td>
            <td>
                <input type="button" id="btnCansole" value="取 消" />
            </td>
        </tr>
    </table>
</form>

5.2.实现提交按钮的事件

 $(function () {
            //0.关闭Jquery的浏览器缓存
            $.ajaxSetup({ cache: false });
            loadPageList(1);
            $("#btnSure").click(DoClick);
        });

5.3.修改的jq

Index.cshtml 修改部分的jquery
Index.cshtml 修改部分的jquery

//------------------------------修改

        //在编辑行
        var editingRow =null;

        //显示修改面板
        function Modify(id,obJec) {
            console.info(id,obJec)
            $.getJSON("/Stu/Get/",{"id":id},function (jsonObj) {
                $("#tbData").css("display","block");

                //判断返回的Statu
                if (jsonObj.Statu =="OK") {
                    //console.info(jsonObj.Data.Name)
                    $("#StudentID").val(jsonObj.Data.StudentID)
                    $("#Name").val(jsonObj.Data.Name);
                    $("#Cid").val(jsonObj.Data.Cid);//班级
                    //性别
                    if (jsonObj.Data.Gender=="男") {
                        $("#GenderFF").removeAttr("Checked");
                        $("#GenderW").removeAttr("Checked");
                        $("#GenderM").attr("Checked","Checked");
                    }else if (jsonObj.Data.Gender=="女") {
                        $("#GenderFF").removeAttr("Checked");
                        $("#GenderM").removeAttr("Checked");
                        $("#GenderW").attr("Checked","Checked");
                    }else {
                        $("#GenderM").removeAttr("Checked");
                        $("#GenderW").removeAttr("Checked");
                        $("#GenderFF").attr("Checked","Checked");
                    }
                    console.info(editingRow);
                    //被点击行
                    editingRow =$(obJec).parent().parent();
                }
            })
        }
        

        //修改提交
        function DoClick() {
            //Form传过去的值,是(Models.Student model)
            var data =$("#tFormData").serialize();
            console.info(data);
            //[HttpPost]
            $.post("/Stu/Modify",data,function (jsonData) {
                if (jsonData.Statu == "OK") {
                    var tds = editingRow.children("td");
                    console.info(tds)
                    tds[2].innerHTML =jsonData.Data.Name;
                    ////根据下拉列表获取它的文本数据,就是它的class.Name了
                    tds[1].innerHTML =$("#Cid option[value="+jsonData.Data.Cid+"]").text() ;
                    tds[3].innerHTML =jsonData.Data.Gender;
                    editingRow =null;//清空编辑行
                    $("#tbData").css("display","none");
                    
                    $.msgBox.showMsgOk(jsonData.Msg);
                }
            },'json');
        }
       

        //------------------------------修改

5.4.后台方法modify

5.4.1.取消验证

public StuController()
        {
            //关闭EF验证,如果不关,就根据配置文件的Nullable来验证(报异常)
            db.Configuration.ValidateOnSaveEnabled = false;
        }

5.4.2.modify方法

        [HttpPost]
        public ActionResult Modify(Models.Student model)
        {
            Models.JsonModel jsonModel = new Models.JsonModel();
            try
            {
                DbEntityEntry entry = db.Entry<Models.Student>(model);
                entry.State = EntityState.Unchanged;
                entry.Property("Name").IsModified = true;
                entry.Property("Cid").IsModified = true;
                entry.Property("Gender").IsModified = true;
                db.SaveChanges();

                jsonModel.Data = model;
                jsonModel.Msg = "更新成功!";
                jsonModel.Statu = "OK";

            }
            catch (Exception ex)
            {
                jsonModel.Msg = "更新异常:"+ex.Message;
                jsonModel.Statu = "Error";
            }
            return Json(jsonModel);
        }

效果图:

1

6.删除

6.1.前台

<a href="javascript:DoDel(${StudentID})"></a>
//------------------------------2.Delete.Start
        function DoDel(id) {
            $.post("/Stu/Del",{id:id},function (jsonObj) {
                if(jsonObj.Statu=="OK"){
                    loadPageList(1);
                    $.msgBox.showMsgOk(jsonObj.Msg);
                }    else {
                    $.msgBox.showMsgErr(jsonObj.Msg);
                }
            });
        }
        //------------------------------2.Delete.End

6.2.后台

/// <summary>
        /// 根据id删除
        /// </summary>
        /// <returns></returns>
        public ActionResult Del()
        {
            Models.JsonModel jsonModel = new Models.JsonModel();
            try
            {
                //6.1 接收数据
                string id = Request.Form["id"];
                //6.2 验证是否为整数
                //6.3 根据id 删除
                Models.Student delModel = new Models.Student()
                {
                    StudentID = int.Parse(id)
                };
                db.Students.Attach(delModel);
                db.Students.Remove(delModel);
                db.SaveChanges();
                jsonModel.Msg = "删除成功!";
                jsonModel.Statu = "OK";

            }
            catch (Exception ex)
            {
                jsonModel.Msg = "更新异常:" + ex.Message;
                jsonModel.Statu = "Error";
            }
            //返回jsonModels
            return Json(jsonModel);
        }
原文地址:https://www.cnblogs.com/tangge/p/3841856.html