MVC view与control数据传递

        MVC是一种常用的web应用程序的设计模式,其优点在于分离复杂的逻辑,我们可以在不关注复杂逻辑的情况下专注于视图设计,同时让代码是也变得方便了很多。view与control之间的数据传递与接收需要我们熟练掌握,通过项目学习,总结一下学到的知识点:

【control->view】

        从control向view端传递最常用的方式是传递json字符串,然后是一些常见数据类型:bool,string等等。

        json(Javascript Object Notation)传递,官方解释为:json是一种轻量级的数据交换格式,采用完全独立于语言的文本格式,根据返回类型不同进行分析:

       (1)数据返回类型为actionResult(称为控制器中的Action,处理请求,返回请求的处理结果)时:

                var data = new
                {
                    total = listData.Count(), //整数型数据
                    rows = listData,  //list类型数据
                   
                };
                return Json(data, JsonRequestBehavior.AllowGet);
        view端接收放到table的过程:

 <table id="tg" url: '/Page/QueryAllClass'>
               <thead style="height: auto;">
                    <tr>
                        <th data-options="field:'CourseId',width:80,align:'center'" hidden>课程ID</th>
                        <th data-options="field:'CourseName',width:80,align:'center'">课程名称</th>
                        <th data-options="field:'TotalScore',width:80,align:'center'">分值</th>
                        <th data-options="field:'ExamineeIsJudgment',width:80,align:'center'" hidden>状态</th>
                        <th data-options="field:'ExamID',width:80,align:'center'" hidden>考试ID</th>
                        <th data-options="field:'ExamName',width:80,align:'center'">考试名称</th>
                        <th data-options="field:'QueryScoreZero',width:80,align:'center',formatter:MainContent">进入判分</th>
                    </tr>
                </thead>
            </table>
        使用getJson方法获取:

$.getJSON("/ExamSelection/QueryExamByTeacher", null, function (data) {
            var columns = new Array();

            
                var column={ field:data.papers.value,title:'总分',width:80,align:'center'}
                columns.push(column);
            
            var column1 = { field: 'QueryScoreZero', title: '进入判分', width: 80, align: 'center', formatter: MainContent }
            columns.push(column1);
            initTable(columns);           
        });


        field后面的字段是返回的rows的属性字段,这样就存在一个问题,返回实体listData可能与table中显示的字段不一致,这样导致数据传输出错,解决的方法:自己再重新定义一个model(在开发过程中往往需要调用其他模块的model,这样修改起来会很麻烦,在自己模块重新定义,会导致很多属性冗余);另一种方法可以在controller端定义需要的数据类型,来承载数据,比如datatable,具体如下:

    (2)数据返回类型为string,拼接table字符:

     

            DataTable ExamInfo = new DataTable();  //定义需要的datatable
            ExamInfo.Columns.Add("CourseId");   //添加列字段
            ExamInfo.Columns.Add("CourseName");
            ExamInfo.Columns.Add("ExamID");
            ExamInfo.Columns.Add("ExamName");
            ExamInfo.Columns.Add("TimeSet");
            ExamInfo.Columns.Add("TotalScores");

      在datatable中赋值:

    ExamInfo.Rows.Add(new object[] { listData[i].CourseId, listData[i].CourseName, listData[i].ExamId, listData[i].ExamName, listData[i].TimeSet, listPaper[0].TotalScore });  //可以将listData实体和listPaper的某些字段都放进去

     特别注意,因为默认定义的datatable是没有行的,所以不能使用下面的字段进行添加数据:

            ExamInfo.Rows[i]["CourseName"] = listData[i].CourseName;
            ExamInfo.Rows[i]["ExamID"] = listData[i].ExamId;
            ExamInfo.Rows[i]["ExamName"] = listData[i].ExamName;
            ExamInfo.Rows[i]["TimeSet"] = listData[i].TimeSet;
            ExamInfo.Rows[i]["TotalScores"] = listPaper[0].TotalScore;
     可以有一种巧妙的方式:在上面的代码开头,让第一个字段通过Add方法,就没有问题了:

                 ExamInfo.Rows.Add(listData[i].CourseId);

     序列化,拼接字符串:

   

            char[] specialChars = new char[] { ',' };
            string JSONstring = "[";

            int index = 0;
            foreach (DataRow dr in ExamInfo.Rows) {
                JSONstring += "{";

                foreach (DataColumn dc in ExamInfo.Columns) {
                    JSONstring += "\"" + dc.ColumnName + "\":\"" + dr[dc].ToString() + "\",";
                }
                JSONstring = JSONstring.TrimEnd(specialChars);
                JSONstring += "},";

                index++;
            }

            JSONstring = JSONstring.TrimEnd(specialChars);
            JSONstring += "]";
            return JSONstring;  //返回datatable接收的json字符串

     (3)返回的数据类型为bool值

       controller端:ViewBag.Message = flag.ToString();

       view端接收:var message = '@ViewBag.Message';

【view->contraller】

      从view端传递到view端的数据类型均可以看做对象类型:

      (1)使用方法传递数据

           var effectRow = new Object();
            effectRow["updated"] = JSON.stringify(rows);

            $.post('/Evaluation/Commit', effectRow, function (rsp) {
                if (rsp) {
                    $.messager.alert("提示", "提交成功了!");

                    $('#dg').datagrid('loadData', { total: 0, rows: [] });
                }
            }, "JSON").error(function () {
                $.messager.alert("提示", "提交错误了!");
            });
     上面代码将整张表以对象的形式传递给controller,接收反序列化得过程:

            string updated = Request.Form["updated"];  //获得传递来的对象

            if (updated != null)
            {

                //去掉反义字符串
                string updatedEdit1 = updated.Replace("\"", "");
                string updatedEdit2 = updatedEdit1.Replace("[", "");
                string updatedEdit3 = updatedEdit2.Replace("]", "");
                string updatedEdit4 = updatedEdit3.Replace("},{", "}");
                string[] updatedEdit = updatedEdit4.Split(new Char[] { '}', '{' }, StringSplitOptions.RemoveEmptyEntries);

                IList<YzDetailEvaluationEntity> staffDetail=new List<YzDetailEvaluationEntity>();
                IList<Guid> settingID = new List<Guid>();
                for (int i = 0; i < updatedEdit.Length; i++)
                {
                    YzDetailEvaluationEntity detailEntity = new YzDetailEvaluationEntity();

                    string pat = @"(?<key>[^,:\s]*):(?<value>[^,:\s]*)"; //反序列化过程
                    //一组之间的数据拿出来
                    //for (int j = 0; j < detailevaluationinfo.Length; j++) {
                    MatchCollection matches = Regex.Matches(updatedEdit[i], pat);

                    Dictionary<string, string> dict = new Dictionary<string, string>();

                    foreach (Match m in matches)   //获得匹配字符串
                    {
                        if (dict.ContainsKey(m.Groups["key"].Value)) continue;//不能重复啊
                        dict.Add(m.Groups["key"].Value, m.Groups["value"].Value);
                    }

 【总结】

       上面所使用的代码比较基础,在实践中经常用到,使用框架封装后使用会更加方便,但我们也要在了解基础的情况下进行封装。相信,在接下来的实践过程中会掌握更加熟练。

       

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 36
    评论
评论 36
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值