MVC view与control数据传递

来源:互联网 发布:mac 安卓sdk环境变量 编辑:程序博客网 时间:2024/05/01 07:29

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

【control->view】

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

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

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

[csharp] view plain copy
  1. var data = new  
  2. {  
  3.     total = listData.Count(), //整数型数据  
  4.     rows = listData,  //list类型数据  
  5.      
  6. };  
  7. return Json(data, JsonRequestBehavior.AllowGet);  
        view端接收放到table的过程:

[html] view plain copy
  1. <table id="tg" url: '/Page/QueryAllClass'>  
  2.               <thead style="height: auto;">  
  3.                    <tr>  
  4.                        <th data-options="field:'CourseId',width:80,align:'center'" hidden>课程ID</th>  
  5.                        <th data-options="field:'CourseName',width:80,align:'center'">课程名称</th>  
  6.                        <th data-options="field:'TotalScore',width:80,align:'center'">分值</th>  
  7.                        <th data-options="field:'ExamineeIsJudgment',width:80,align:'center'" hidden>状态</th>  
  8.                        <th data-options="field:'ExamID',width:80,align:'center'" hidden>考试ID</th>  
  9.                        <th data-options="field:'ExamName',width:80,align:'center'">考试名称</th>  
  10.                        <th data-options="field:'QueryScoreZero',width:80,align:'center',formatter:MainContent">进入判分</th>  
  11.                    </tr>  
  12.                </thead>  
  13.            </table>  
        使用getJson方法获取:

[html] view plain copy
  1. $.getJSON("/ExamSelection/QueryExamByTeacher", null, function (data) {  
  2.             var columns = new Array();  
  3.   
  4.               
  5.                 var column={ field:data.papers.value,title:'总分',width:80,align:'center'}  
  6.                 columns.push(column);  
  7.               
  8.             var column1 = { field: 'QueryScoreZero', title: '进入判分', width: 80, align: 'center', formatter: MainContent }  
  9.             columns.push(column1);  
  10.             initTable(columns);             
  11.         });  


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

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

     

[csharp] view plain copy
  1. DataTable ExamInfo = new DataTable();  //定义需要的datatable  
  2. ExamInfo.Columns.Add("CourseId");   //添加列字段  
  3. ExamInfo.Columns.Add("CourseName");  
  4. ExamInfo.Columns.Add("ExamID");  
  5. ExamInfo.Columns.Add("ExamName");  
  6. ExamInfo.Columns.Add("TimeSet");  
  7. ExamInfo.Columns.Add("TotalScores");  

      在datatable中赋值:

[csharp] view plain copy
  1. 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是没有行的,所以不能使用下面的字段进行添加数据:

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

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

     序列化,拼接字符串:

   

[csharp] view plain copy
  1. char[] specialChars = new char[] { ',' };  
  2. string JSONstring = "[";  
  3.   
  4. int index = 0;  
  5. foreach (DataRow dr in ExamInfo.Rows) {  
  6.     JSONstring += "{";  
  7.   
  8.     foreach (DataColumn dc in ExamInfo.Columns) {  
  9.         JSONstring += "\"" + dc.ColumnName + "\":\"" + dr[dc].ToString() + "\",";  
  10.     }  
  11.     JSONstring = JSONstring.TrimEnd(specialChars);  
  12.     JSONstring += "},";  
  13.   
  14.     index++;  
  15. }  
  16.   
  17. JSONstring = JSONstring.TrimEnd(specialChars);  
  18. JSONstring += "]";  
  19. return JSONstring;  //返回datatable接收的json字符串  

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

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

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

【view->contraller】

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

      (1)使用方法传递数据

[html] view plain copy
  1. var effectRow = new Object();  
  2.  effectRow["updated"] = JSON.stringify(rows);  
  3.   
  4.  $.post('/Evaluation/Commit', effectRow, function (rsp) {  
  5.      if (rsp) {  
  6.          $.messager.alert("提示", "提交成功了!");  
  7.   
  8.          $('#dg').datagrid('loadData', { total: 0, rows: [] });  
  9.      }  
  10.  }, "JSON").error(function () {  
  11.      $.messager.alert("提示", "提交错误了!");  
  12.  });  
     上面代码将整张表以对象的形式传递给controller,接收反序列化得过程:

[csharp] view plain copy
  1. string updated = Request.Form["updated"];  //获得传递来的对象  
  2.   
  3. if (updated != null)  
  4. {  
  5.   
  6.     //去掉反义字符串  
  7.     string updatedEdit1 = updated.Replace("\"""");  
  8.     string updatedEdit2 = updatedEdit1.Replace("[""");  
  9.     string updatedEdit3 = updatedEdit2.Replace("]""");  
  10.     string updatedEdit4 = updatedEdit3.Replace("},{""}");  
  11.     string[] updatedEdit = updatedEdit4.Split(new Char[] { '}''{' }, StringSplitOptions.RemoveEmptyEntries);  
  12.   
  13.     IList<YzDetailEvaluationEntity> staffDetail=new List<YzDetailEvaluationEntity>();  
  14.     IList<Guid> settingID = new List<Guid>();  
  15.     for (int i = 0; i < updatedEdit.Length; i++)  
  16.     {  
  17.         YzDetailEvaluationEntity detailEntity = new YzDetailEvaluationEntity();  
  18.   
  19.         string pat = @"(?<key>[^,:\s]*):(?<value>[^,:\s]*)"//反序列化过程  
  20.         //一组之间的数据拿出来  
  21.         //for (int j = 0; j < detailevaluationinfo.Length; j++) {  
  22.         MatchCollection matches = Regex.Matches(updatedEdit[i], pat);  
  23.   
  24.         Dictionary<stringstring> dict = new Dictionary<stringstring>();  
  25.   
  26.         foreach (Match m in matches)   //获得匹配字符串  
  27.         {  
  28.             if (dict.ContainsKey(m.Groups["key"].Value)) continue;//不能重复啊  
  29.             dict.Add(m.Groups["key"].Value, m.Groups["value"].Value);  
  30.         }  

 【总结】

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

0 0
原创粉丝点击